code
stringlengths
31
1.05M
apis
list
extract_api
stringlengths
97
1.91M
import numpy as np import nibabel as nib from numpy.testing import (assert_equal, assert_almost_equal, run_module_suite) from dipy.data import get_fnames from dipy.segment.bundles import RecoBundles from dipy.tracking.distances import bundles_distances_mam from dipy.tracking.streamline import Streamlines from dipy.segment.clustering import qbx_and_merge streams, hdr = nib.trackvis.read(get_fnames('fornix')) fornix = [s[0] for s in streams] f = Streamlines(fornix) f1 = f.copy() f2 = f1[:20].copy() f2._data += np.array([50, 0, 0]) f3 = f1[200:].copy() f3._data += np.array([100, 0, 0]) f.extend(f2) f.extend(f3) def test_rb_check_defaults(): rb = RecoBundles(f, greater_than=0, clust_thr=10) rec_trans, rec_labels = rb.recognize(model_bundle=f2, model_clust_thr=5., reduction_thr=10) D = bundles_distances_mam(f2, f[rec_labels]) # check if the bundle is recognized correctly if len(f2) == len(rec_labels): for row in D: assert_equal(row.min(), 0) refine_trans, refine_labels = rb.refine(model_bundle=f2, pruned_streamlines=rec_trans, model_clust_thr=5., reduction_thr=10) D = bundles_distances_mam(f2, f[refine_labels]) # check if the bundle is recognized correctly for row in D: assert_equal(row.min(), 0) def test_rb_disable_slr(): rb = RecoBundles(f, greater_than=0, clust_thr=10) rec_trans, rec_labels = rb.recognize(model_bundle=f2, model_clust_thr=5., reduction_thr=10, slr=False) D = bundles_distances_mam(f2, f[rec_labels]) # check if the bundle is recognized correctly if len(f2) == len(rec_labels): for row in D: assert_equal(row.min(), 0) refine_trans, refine_labels = rb.refine(model_bundle=f2, pruned_streamlines=rec_trans, model_clust_thr=5., reduction_thr=10) D = bundles_distances_mam(f2, f[refine_labels]) # check if the bundle is recognized correctly for row in D: assert_equal(row.min(), 0) def test_rb_slr_threads(): rng_multi = np.random.RandomState(42) rb_multi = RecoBundles(f, greater_than=0, clust_thr=10, rng=np.random.RandomState(42)) rec_trans_multi_threads, _ = rb_multi.recognize(model_bundle=f2, model_clust_thr=5., reduction_thr=10, slr=True, slr_num_threads=None) rb_single = RecoBundles(f, greater_than=0, clust_thr=10, rng=np.random.RandomState(42)) rec_trans_single_thread, _ = rb_single.recognize(model_bundle=f2, model_clust_thr=5., reduction_thr=10, slr=True, slr_num_threads=1) D = bundles_distances_mam(rec_trans_multi_threads, rec_trans_single_thread) # check if the bundle is recognized correctly # multi-threading prevent an exact match for row in D: assert_almost_equal(row.min(), 0, decimal=4) def test_rb_no_verbose_and_mam(): rb = RecoBundles(f, greater_than=0, clust_thr=10, verbose=False) rec_trans, rec_labels = rb.recognize(model_bundle=f2, model_clust_thr=5., reduction_thr=10, slr=True, pruning_distance='mam') D = bundles_distances_mam(f2, f[rec_labels]) # check if the bundle is recognized correctly if len(f2) == len(rec_labels): for row in D: assert_equal(row.min(), 0) refine_trans, refine_labels = rb.refine(model_bundle=f2, pruned_streamlines=rec_trans, model_clust_thr=5., reduction_thr=10) D = bundles_distances_mam(f2, f[refine_labels]) # check if the bundle is recognized correctly for row in D: assert_equal(row.min(), 0) def test_rb_clustermap(): cluster_map = qbx_and_merge(f, thresholds=[40, 25, 20, 10]) rb = RecoBundles(f, greater_than=0, less_than=1000000, cluster_map=cluster_map, clust_thr=10) rec_trans, rec_labels = rb.recognize(model_bundle=f2, model_clust_thr=5., reduction_thr=10) D = bundles_distances_mam(f2, f[rec_labels]) # check if the bundle is recognized correctly if len(f2) == len(rec_labels): for row in D: assert_equal(row.min(), 0) refine_trans, refine_labels = rb.refine(model_bundle=f2, pruned_streamlines=rec_trans, model_clust_thr=5., reduction_thr=10) D = bundles_distances_mam(f2, f[refine_labels]) # check if the bundle is recognized correctly for row in D: assert_equal(row.min(), 0) def test_rb_no_neighb(): # what if no neighbors are found? No recognition b = Streamlines(fornix) b1 = b.copy() b2 = b1[:20].copy() b2._data += np.array([100, 0, 0]) b3 = b1[:20].copy() b3._data += np.array([300, 0, 0]) b.extend(b3) rb = RecoBundles(b, greater_than=0, clust_thr=10) rec_trans, rec_labels = rb.recognize(model_bundle=b2, model_clust_thr=5., reduction_thr=10) if len(rec_trans) > 0: refine_trans, refine_labels = rb.refine(model_bundle=b2, pruned_streamlines=rec_trans, model_clust_thr=5., reduction_thr=10) assert_equal(len(refine_labels), 0) assert_equal(len(refine_trans), 0) else: assert_equal(len(rec_labels), 0) assert_equal(len(rec_trans), 0) def test_rb_reduction_mam(): rb = RecoBundles(f, greater_than=0, clust_thr=10, verbose=True) rec_trans, rec_labels = rb.recognize(model_bundle=f2, model_clust_thr=5., reduction_thr=10, reduction_distance='mam', slr=True, slr_metric='asymmetric', pruning_distance='mam') D = bundles_distances_mam(f2, f[rec_labels]) # check if the bundle is recognized correctly if len(f2) == len(rec_labels): for row in D: assert_equal(row.min(), 0) refine_trans, refine_labels = rb.refine(model_bundle=f2, pruned_streamlines=rec_trans, model_clust_thr=5., reduction_thr=10) D = bundles_distances_mam(f2, f[refine_labels]) # check if the bundle is recognized correctly for row in D: assert_equal(row.min(), 0) if __name__ == '__main__': run_module_suite()
[ "dipy.tracking.streamline.Streamlines", "dipy.data.get_fnames", "dipy.segment.bundles.RecoBundles", "numpy.testing.run_module_suite", "numpy.random.RandomState", "numpy.array", "dipy.segment.clustering.qbx_and_merge", "dipy.tracking.distances.bundles_distances_mam" ]
[((505, 524), 'dipy.tracking.streamline.Streamlines', 'Streamlines', (['fornix'], {}), '(fornix)\n', (516, 524), False, 'from dipy.tracking.streamline import Streamlines\n'), ((572, 592), 'numpy.array', 'np.array', (['[50, 0, 0]'], {}), '([50, 0, 0])\n', (580, 592), True, 'import numpy as np\n'), ((627, 648), 'numpy.array', 'np.array', (['[100, 0, 0]'], {}), '([100, 0, 0])\n', (635, 648), True, 'import numpy as np\n'), ((445, 465), 'dipy.data.get_fnames', 'get_fnames', (['"""fornix"""'], {}), "('fornix')\n", (455, 465), False, 'from dipy.data import get_fnames\n'), ((718, 762), 'dipy.segment.bundles.RecoBundles', 'RecoBundles', (['f'], {'greater_than': '(0)', 'clust_thr': '(10)'}), '(f, greater_than=0, clust_thr=10)\n', (729, 762), False, 'from dipy.segment.bundles import RecoBundles\n'), ((951, 991), 'dipy.tracking.distances.bundles_distances_mam', 'bundles_distances_mam', (['f2', 'f[rec_labels]'], {}), '(f2, f[rec_labels])\n', (972, 991), False, 'from dipy.tracking.distances import bundles_distances_mam\n'), ((1410, 1453), 'dipy.tracking.distances.bundles_distances_mam', 'bundles_distances_mam', (['f2', 'f[refine_labels]'], {}), '(f2, f[refine_labels])\n', (1431, 1453), False, 'from dipy.tracking.distances import bundles_distances_mam\n'), ((1597, 1641), 'dipy.segment.bundles.RecoBundles', 'RecoBundles', (['f'], {'greater_than': '(0)', 'clust_thr': '(10)'}), '(f, greater_than=0, clust_thr=10)\n', (1608, 1641), False, 'from dipy.segment.bundles import RecoBundles\n'), ((1882, 1922), 'dipy.tracking.distances.bundles_distances_mam', 'bundles_distances_mam', (['f2', 'f[rec_labels]'], {}), '(f2, f[rec_labels])\n', (1903, 1922), False, 'from dipy.tracking.distances import bundles_distances_mam\n'), ((2341, 2384), 'dipy.tracking.distances.bundles_distances_mam', 'bundles_distances_mam', (['f2', 'f[refine_labels]'], {}), '(f2, f[refine_labels])\n', (2362, 2384), False, 'from dipy.tracking.distances import bundles_distances_mam\n'), ((2535, 2560), 'numpy.random.RandomState', 'np.random.RandomState', (['(42)'], {}), '(42)\n', (2556, 2560), True, 'import numpy as np\n'), ((3477, 3548), 'dipy.tracking.distances.bundles_distances_mam', 'bundles_distances_mam', (['rec_trans_multi_threads', 'rec_trans_single_thread'], {}), '(rec_trans_multi_threads, rec_trans_single_thread)\n', (3498, 3548), False, 'from dipy.tracking.distances import bundles_distances_mam\n'), ((3762, 3821), 'dipy.segment.bundles.RecoBundles', 'RecoBundles', (['f'], {'greater_than': '(0)', 'clust_thr': '(10)', 'verbose': '(False)'}), '(f, greater_than=0, clust_thr=10, verbose=False)\n', (3773, 3821), False, 'from dipy.segment.bundles import RecoBundles\n'), ((4126, 4166), 'dipy.tracking.distances.bundles_distances_mam', 'bundles_distances_mam', (['f2', 'f[rec_labels]'], {}), '(f2, f[rec_labels])\n', (4147, 4166), False, 'from dipy.tracking.distances import bundles_distances_mam\n'), ((4585, 4628), 'dipy.tracking.distances.bundles_distances_mam', 'bundles_distances_mam', (['f2', 'f[refine_labels]'], {}), '(f2, f[refine_labels])\n', (4606, 4628), False, 'from dipy.tracking.distances import bundles_distances_mam\n'), ((4780, 4825), 'dipy.segment.clustering.qbx_and_merge', 'qbx_and_merge', (['f'], {'thresholds': '[40, 25, 20, 10]'}), '(f, thresholds=[40, 25, 20, 10])\n', (4793, 4825), False, 'from dipy.segment.clustering import qbx_and_merge\n'), ((4836, 4928), 'dipy.segment.bundles.RecoBundles', 'RecoBundles', (['f'], {'greater_than': '(0)', 'less_than': '(1000000)', 'cluster_map': 'cluster_map', 'clust_thr': '(10)'}), '(f, greater_than=0, less_than=1000000, cluster_map=cluster_map,\n clust_thr=10)\n', (4847, 4928), False, 'from dipy.segment.bundles import RecoBundles\n'), ((5133, 5173), 'dipy.tracking.distances.bundles_distances_mam', 'bundles_distances_mam', (['f2', 'f[rec_labels]'], {}), '(f2, f[rec_labels])\n', (5154, 5173), False, 'from dipy.tracking.distances import bundles_distances_mam\n'), ((5592, 5635), 'dipy.tracking.distances.bundles_distances_mam', 'bundles_distances_mam', (['f2', 'f[refine_labels]'], {}), '(f2, f[refine_labels])\n', (5613, 5635), False, 'from dipy.tracking.distances import bundles_distances_mam\n'), ((5829, 5848), 'dipy.tracking.streamline.Streamlines', 'Streamlines', (['fornix'], {}), '(fornix)\n', (5840, 5848), False, 'from dipy.tracking.streamline import Streamlines\n'), ((5908, 5929), 'numpy.array', 'np.array', (['[100, 0, 0]'], {}), '([100, 0, 0])\n', (5916, 5929), True, 'import numpy as np\n'), ((5971, 5992), 'numpy.array', 'np.array', (['[300, 0, 0]'], {}), '([300, 0, 0])\n', (5979, 5992), True, 'import numpy as np\n'), ((6021, 6065), 'dipy.segment.bundles.RecoBundles', 'RecoBundles', (['b'], {'greater_than': '(0)', 'clust_thr': '(10)'}), '(b, greater_than=0, clust_thr=10)\n', (6032, 6065), False, 'from dipy.segment.bundles import RecoBundles\n'), ((6771, 6829), 'dipy.segment.bundles.RecoBundles', 'RecoBundles', (['f'], {'greater_than': '(0)', 'clust_thr': '(10)', 'verbose': '(True)'}), '(f, greater_than=0, clust_thr=10, verbose=True)\n', (6782, 6829), False, 'from dipy.segment.bundles import RecoBundles\n'), ((7267, 7307), 'dipy.tracking.distances.bundles_distances_mam', 'bundles_distances_mam', (['f2', 'f[rec_labels]'], {}), '(f2, f[rec_labels])\n', (7288, 7307), False, 'from dipy.tracking.distances import bundles_distances_mam\n'), ((7726, 7769), 'dipy.tracking.distances.bundles_distances_mam', 'bundles_distances_mam', (['f2', 'f[refine_labels]'], {}), '(f2, f[refine_labels])\n', (7747, 7769), False, 'from dipy.tracking.distances import bundles_distances_mam\n'), ((7908, 7926), 'numpy.testing.run_module_suite', 'run_module_suite', ([], {}), '()\n', (7924, 7926), False, 'from numpy.testing import assert_equal, assert_almost_equal, run_module_suite\n'), ((2652, 2677), 'numpy.random.RandomState', 'np.random.RandomState', (['(42)'], {}), '(42)\n', (2673, 2677), True, 'import numpy as np\n'), ((3120, 3145), 'numpy.random.RandomState', 'np.random.RandomState', (['(42)'], {}), '(42)\n', (3141, 3145), True, 'import numpy as np\n')]
import numpy as np from .planar_graph import PlanarGraph from .planar_graph_edges import PlanarGraphEdges from .. import common_utils class PlanarGraphConstructor: """ A static class with different planar graph construction methods. """ @staticmethod def construct_subgraph(graph, subgraph_vertices_mask, subgraph_edges_mask): """ Linear algorithm for subgraph construction. Parameters ---------- graph : PlanarGraph subgraph_vertices_mask : array_like, boolean Boolean mask of vertices to leave in subgraph. subgraph_edges_mask : array_like, boolean Boolean mask of edges to leave in subgraph. Returns ------- new_vertices_mapping : array_like, int32 Mapping from `graph` vertices to corresponding `subgraph` vertices. If `graph` vertex is deleted, `-1` is substituted. new_edge_indices_mapping : array_like, int32 Mapping from `graph` edge indices to corresponding `subgraph` edge indices. If `graph` edge index is deleted, `-1` is substituted. subgraph : PlanarGraph Result subgraph """ vertex_costs = graph.vertex_costs[subgraph_vertices_mask] new_vertices_mapping = -np.ones(graph.size, dtype=int) current_new_vertex = 0 for vertex, is_in_subgraph in enumerate(subgraph_vertices_mask): if is_in_subgraph: new_vertices_mapping[vertex] = current_new_vertex current_new_vertex += 1 edges_count = 0 new_edge_indices_mapping = -np.ones(graph.edges_count, dtype=int) for edge_index in range(graph.edges_count): edge_vertex1 = graph.edges.vertex1[edge_index] edge_vertex2 = graph.edges.vertex2[edge_index] if subgraph_vertices_mask[edge_vertex1] and subgraph_vertices_mask[edge_vertex2] and \ subgraph_edges_mask[edge_index]: new_edge_indices_mapping[edge_index] = edges_count edges_count += 1 edges = PlanarGraphEdges(edges_count) for edge_index in range(graph.edges_count): edge_vertex1 = graph.edges.vertex1[edge_index] edge_vertex2 = graph.edges.vertex2[edge_index] if subgraph_vertices_mask[edge_vertex1] and subgraph_vertices_mask[edge_vertex2] and \ subgraph_edges_mask[edge_index]: edges.append(new_vertices_mapping[edge_vertex1], new_vertices_mapping[edge_vertex2]) incident_edge_example_indices = -np.ones(len(vertex_costs), dtype=int) for vertex, is_in_subgraph in enumerate(subgraph_vertices_mask): if is_in_subgraph: new_vertex = new_vertices_mapping[vertex] first_new_edge_index = -1 previous_new_edge_index = -1 for edge_index in graph.get_incident_edge_indices(vertex): new_edge_index = new_edge_indices_mapping[edge_index] if new_edge_index != -1: if previous_new_edge_index == -1: incident_edge_example_indices[new_vertex] = new_edge_index first_new_edge_index = new_edge_index else: edges.set_previous_edge(new_edge_index, new_vertex, previous_new_edge_index) previous_new_edge_index = new_edge_index if first_new_edge_index != -1: edges.set_previous_edge(first_new_edge_index, new_vertex, previous_new_edge_index) return new_vertices_mapping, new_edge_indices_mapping, PlanarGraph(vertex_costs, incident_edge_example_indices, edges) @staticmethod def clone_graph(graph): """ Graph cloning. Parameters ---------- graph : PlanarGraph Returns ------- PlanarGraph The same graph up to different incident edge examples. """ _, _, graph = PlanarGraphConstructor.construct_subgraph(graph, np.ones(graph.size, dtype=bool), np.ones(graph.edges_count, dtype=bool)) return graph @staticmethod def _create_edges_and_map_adjacencies(adjacent_vertices): edges = PlanarGraphEdges(sum(len(vertices) for vertices in adjacent_vertices)//2) edge_indices_by_adjacencies = {} for vertex, vertex_adjacent_vertices in enumerate(adjacent_vertices): for adjacent_vertex in vertex_adjacent_vertices: if (vertex, adjacent_vertex) not in edge_indices_by_adjacencies: edge_indices_by_adjacencies[(vertex, adjacent_vertex)] = edges.size edge_indices_by_adjacencies[(adjacent_vertex, vertex)] = edges.size edges.append(vertex, adjacent_vertex) return edges, edge_indices_by_adjacencies @staticmethod def construct_from_ordered_adjacencies(ordered_adjacencies): """ Convenient method for constructing planar graph. Parameters ---------- ordered_adjacencies : list of list of int The list, where for each vertex the list of its adjacent vertices is provided in the order of ccw traversal (or cw traversal, it's just a convention). For instance, `[[1, 2, 3, 4], [0], [0], [0], [0]]` would encode a "star" graph with 4 edges. Returns ------- PlanarGraph Notes ----- Only normal graphs are supported, i.e. no multiple edges or loops. """ vertices_count = len(ordered_adjacencies) vertex_costs = np.ones(vertices_count, dtype=float)/vertices_count edges, edge_indices_by_adjacencies = \ PlanarGraphConstructor._create_edges_and_map_adjacencies(ordered_adjacencies) incident_edge_example_indices = -np.ones(vertices_count, dtype=int) for vertex, vertex_ordered_adjacencies in enumerate(ordered_adjacencies): adjacent_vertices_count = len(vertex_ordered_adjacencies) if adjacent_vertices_count != 0: first_adjacent_vertex = vertex_ordered_adjacencies[0] first_incident_edge_index = edge_indices_by_adjacencies[(vertex, first_adjacent_vertex)] incident_edge_example_indices[vertex] = first_incident_edge_index for adjacent_vertex_index, adjacent_vertex in \ enumerate(vertex_ordered_adjacencies): incident_edge_index = edge_indices_by_adjacencies[(vertex, adjacent_vertex)] next_adjacent_vertex_index = (adjacent_vertex_index + 1)%adjacent_vertices_count next_adjacent_vertex = \ vertex_ordered_adjacencies[next_adjacent_vertex_index] next_incident_edge_index = \ edge_indices_by_adjacencies[(vertex, next_adjacent_vertex)] edges.set_next_edge(incident_edge_index, vertex, next_incident_edge_index) return PlanarGraph(vertex_costs, incident_edge_example_indices, edges) @staticmethod def remove_double_edges(graph): connecting_edge_indices = common_utils.repeat_int(-1, graph.size) new_edge_indices_mapping1 = np.arange(graph.edges_count, dtype=int) edge_indices_mask = common_utils.repeat_bool(True, graph.edges_count) for vertex in range(graph.size): for edge_index in graph.get_incident_edge_indices(vertex): adjacent_vertex = graph.edges.get_opposite_vertex(edge_index, vertex) if connecting_edge_indices[adjacent_vertex] != -1: edge_indices_mask[edge_index] = False new_edge_indices_mapping1[edge_index] = connecting_edge_indices[adjacent_vertex] else: if edge_indices_mask[edge_index]: connecting_edge_indices[adjacent_vertex] = edge_index for adjacent_vertex in graph.get_adjacent_vertices(vertex): connecting_edge_indices[adjacent_vertex] = -1 new_vertices_mapping, new_edge_indices_mapping2, graph = \ PlanarGraphConstructor.construct_subgraph(graph, common_utils.repeat_bool(True, graph.size), edge_indices_mask) new_edge_indices_mapping = new_edge_indices_mapping2[new_edge_indices_mapping1] return new_vertices_mapping, new_edge_indices_mapping, graph
[ "numpy.arange", "numpy.ones" ]
[((7463, 7502), 'numpy.arange', 'np.arange', (['graph.edges_count'], {'dtype': 'int'}), '(graph.edges_count, dtype=int)\n', (7472, 7502), True, 'import numpy as np\n'), ((1303, 1333), 'numpy.ones', 'np.ones', (['graph.size'], {'dtype': 'int'}), '(graph.size, dtype=int)\n', (1310, 1333), True, 'import numpy as np\n'), ((1637, 1674), 'numpy.ones', 'np.ones', (['graph.edges_count'], {'dtype': 'int'}), '(graph.edges_count, dtype=int)\n', (1644, 1674), True, 'import numpy as np\n'), ((4179, 4210), 'numpy.ones', 'np.ones', (['graph.size'], {'dtype': 'bool'}), '(graph.size, dtype=bool)\n', (4186, 4210), True, 'import numpy as np\n'), ((4212, 4250), 'numpy.ones', 'np.ones', (['graph.edges_count'], {'dtype': 'bool'}), '(graph.edges_count, dtype=bool)\n', (4219, 4250), True, 'import numpy as np\n'), ((5775, 5811), 'numpy.ones', 'np.ones', (['vertices_count'], {'dtype': 'float'}), '(vertices_count, dtype=float)\n', (5782, 5811), True, 'import numpy as np\n'), ((6011, 6045), 'numpy.ones', 'np.ones', (['vertices_count'], {'dtype': 'int'}), '(vertices_count, dtype=int)\n', (6018, 6045), True, 'import numpy as np\n')]
# %% [markdown] """ calculate ODNP using DNPLab =========================== This example demonstrates how to use the dnplab.dnpHydration module """ # %% # %% [markdown] # First import dnplab and numpy, import dnplab import numpy as np # %% # %% [markdown] # 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, Enhancements = [] # list of signal enhancements Enhancement_powers = [] # list of powers in Watts corresponding to Enhancements T1s = [] # list of T1 values in seconds T1_powers = [] # list of powers in Watts corresponding to T1s inputs = { 'E_array' : np.array(Enhancements), 'E_powers' : np.array(Enhancement_powers), 'T1_array' : np.array(T1s), 'T1_powers' : np.array(T1_powers), 'T10': 2.0, # T1 measured with power=0 'T100': 2.5, # T1 measured with SL=0 and power=0 'spin_C': 100, # spin concentration in micromolar 'field': 350, # magnetic field in mT 'smax_model': 'tethered', # choice of smax model 'interpolate_method': 'second_order' # choice of interpolation method } # %% # %% [markdown] # Now you can either create a workspace and add the dictionary under the key **'hydration_inputs'**, workspace = dnplab.create_workspace('hydration_inputs', inputs) # %% # %% [markdown] # Or add to an existing workspace, workspace.add('hydration_inputs', inputs) # %% # %% [markdown] # 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, constants = { 'ksigma_bulk': 95.4, # bulk ksigma value 'krho_bulk': 353.4, # bulk krho value 'klow_bulk': 366, # bulk klow value 'tcorr_bulk': 54, # bulk tcorr value 'D_H2O': 2.3e-9, # bulk water diffusivity 'D_SL': 4.1e-10, # diffusivity of spin probe in bulk water 'delta_T1_water': 1, # change in water proton T1 due to microwaves 'T1_water': 2.5, # T1 of bulk water protons 'macro_C': 100, # concentration of macromolecule in uM } workspace.add('hydration_constants', constants) # %% # %% [markdown] # Next, pass the workspace to dnplab.dnpHydration.hydration to perform calculations using, hydration_results = dnplab.dnpHydration.hydration(workspace) # %% # %% [markdown] # or operate in-place with: dnplab.dnpHydration.hydration(workspace) # %% # %% [markdown] # For use without creating a DNPLab workspace simply skip the above steps and pass the dictionaries to dnpHydration directly, hydration_results = dnplab.dnpHydration.odnp(inputs=inputs, constants=constants) # %%
[ "dnplab.dnpHydration.hydration", "dnplab.create_workspace", "dnplab.dnpHydration.odnp", "numpy.array" ]
[((1386, 1437), 'dnplab.create_workspace', 'dnplab.create_workspace', (['"""hydration_inputs"""', 'inputs'], {}), "('hydration_inputs', inputs)\n", (1409, 1437), False, 'import dnplab\n'), ((2571, 2611), 'dnplab.dnpHydration.hydration', 'dnplab.dnpHydration.hydration', (['workspace'], {}), '(workspace)\n', (2600, 2611), False, 'import dnplab\n'), ((2662, 2702), 'dnplab.dnpHydration.hydration', 'dnplab.dnpHydration.hydration', (['workspace'], {}), '(workspace)\n', (2691, 2702), False, 'import dnplab\n'), ((2872, 2932), 'dnplab.dnpHydration.odnp', 'dnplab.dnpHydration.odnp', ([], {'inputs': 'inputs', 'constants': 'constants'}), '(inputs=inputs, constants=constants)\n', (2896, 2932), False, 'import dnplab\n'), ((725, 747), 'numpy.array', 'np.array', (['Enhancements'], {}), '(Enhancements)\n', (733, 747), True, 'import numpy as np\n'), ((772, 800), 'numpy.array', 'np.array', (['Enhancement_powers'], {}), '(Enhancement_powers)\n', (780, 800), True, 'import numpy as np\n'), ((825, 838), 'numpy.array', 'np.array', (['T1s'], {}), '(T1s)\n', (833, 838), True, 'import numpy as np\n'), ((864, 883), 'numpy.array', 'np.array', (['T1_powers'], {}), '(T1_powers)\n', (872, 883), True, 'import numpy as np\n')]
# -*- coding: utf-8 -*- """ Created on Fri Sep 18 18:42:30 2020 @author: <NAME> """ import numpy as np import pandas as pd import os from sklearn import metrics # 改变工作目录 os.chdir(r"C:\Users\<NAME>\Desktop\携程网点评内容情感分析") # 读取数据 test_pred = np.load("test_pred.npy") y_test = np.load("y_test.npy") y_train = np.load("y_train.npy") # 包含字符串元素的array,每一个元素都是object,需要加上allow_pickle=True。默认是False,防止读入恶意信息。 X_test = np.load("X_test.npy", allow_pickle=True) X_train = np.load("X_train.npy", allow_pickle=True) unique, counts = np.unique(y_train, return_counts=True) # 检查一下分的是否均匀 dict(zip(unique, counts)) # 评估模型预测结果 # 准确率 metrics.accuracy_score(y_test, test_pred) # 召回率 metrics.recall_score(y_test, test_pred, average='binary') # precision metrics.precision_score(y_test, test_pred, average='binary') # 混淆矩阵 metrics.confusion_matrix(y_test, test_pred) # 计算ROC值 metrics.roc_auc_score(y_test, test_pred)
[ "numpy.load", "sklearn.metrics.accuracy_score", "sklearn.metrics.recall_score", "sklearn.metrics.roc_auc_score", "sklearn.metrics.precision_score", "sklearn.metrics.confusion_matrix", "os.chdir", "numpy.unique" ]
[((174, 225), 'os.chdir', 'os.chdir', (['"""C:\\\\Users\\\\<NAME>\\\\Desktop\\\\携程网点评内容情感分析"""'], {}), "('C:\\\\Users\\\\<NAME>\\\\Desktop\\\\携程网点评内容情感分析')\n", (182, 225), False, 'import os\n'), ((242, 266), 'numpy.load', 'np.load', (['"""test_pred.npy"""'], {}), "('test_pred.npy')\n", (249, 266), True, 'import numpy as np\n'), ((276, 297), 'numpy.load', 'np.load', (['"""y_test.npy"""'], {}), "('y_test.npy')\n", (283, 297), True, 'import numpy as np\n'), ((308, 330), 'numpy.load', 'np.load', (['"""y_train.npy"""'], {}), "('y_train.npy')\n", (315, 330), True, 'import numpy as np\n'), ((411, 451), 'numpy.load', 'np.load', (['"""X_test.npy"""'], {'allow_pickle': '(True)'}), "('X_test.npy', allow_pickle=True)\n", (418, 451), True, 'import numpy as np\n'), ((462, 503), 'numpy.load', 'np.load', (['"""X_train.npy"""'], {'allow_pickle': '(True)'}), "('X_train.npy', allow_pickle=True)\n", (469, 503), True, 'import numpy as np\n'), ((525, 563), 'numpy.unique', 'np.unique', (['y_train'], {'return_counts': '(True)'}), '(y_train, return_counts=True)\n', (534, 563), True, 'import numpy as np\n'), ((624, 665), 'sklearn.metrics.accuracy_score', 'metrics.accuracy_score', (['y_test', 'test_pred'], {}), '(y_test, test_pred)\n', (646, 665), False, 'from sklearn import metrics\n'), ((672, 729), 'sklearn.metrics.recall_score', 'metrics.recall_score', (['y_test', 'test_pred'], {'average': '"""binary"""'}), "(y_test, test_pred, average='binary')\n", (692, 729), False, 'from sklearn import metrics\n'), ((742, 802), 'sklearn.metrics.precision_score', 'metrics.precision_score', (['y_test', 'test_pred'], {'average': '"""binary"""'}), "(y_test, test_pred, average='binary')\n", (765, 802), False, 'from sklearn import metrics\n'), ((810, 853), 'sklearn.metrics.confusion_matrix', 'metrics.confusion_matrix', (['y_test', 'test_pred'], {}), '(y_test, test_pred)\n', (834, 853), False, 'from sklearn import metrics\n'), ((863, 903), 'sklearn.metrics.roc_auc_score', 'metrics.roc_auc_score', (['y_test', 'test_pred'], {}), '(y_test, test_pred)\n', (884, 903), False, 'from sklearn import metrics\n')]
import numpy as np from . import options import os from .base_gsm import * #from dlc import * from .pes import * import pybel as pb import sys class GSM(Base_Method): def __init__( self, options, ): super(GSM,self).__init__(options) print(" Forming Union of primitive coordinates") self.nodes[0].coord_obj = self.nodes[0].coord_obj.union(self.nodes[-1].coord_obj,self.nodes[0].xyz) self.nodes[0].form_Primitive_Hessian() print(" Done forming union") self.nodes[-1].PES.lot.node_id = self.nnodes-1 self.nodes[-1].coord_obj = self.nodes[0].coord_obj.copy(self.nodes[-1].xyz) self.nodes[-1].form_Primitive_Hessian() # this tests if the primitives are the same assert self.nodes[0].coord_obj == self.nodes[-1].coord_obj, "They should be the same." print(" Primitive Internal Coordinates") print(self.nodes[0].primitive_internal_coordinates) print(" number of primitives is", self.nodes[0].num_primitives) def restart_string(self,xyzbase='restart'): self.growth_direction=0 xyzfile=xyzbase+".xyz" with open(xyzfile) as f: nlines = sum(1 for _ in f) #print "number of lines is ", nlines with open(xyzfile) as f: natoms = int(f.readlines()[2]) #print "number of atoms is ",natoms nstructs = (nlines-6)/ (natoms+5) #this is for three blocks after GEOCON #print "number of structures in restart file is %i" % nstructs coords=[] grmss = [] atomic_symbols=[] dE = [] with open(xyzfile) as f: f.readline() f.readline() #header lines # get coords for struct in range(nstructs): tmpcoords=np.zeros((natoms,3)) f.readline() #natoms f.readline() #space for a in range(natoms): line=f.readline() tmp = line.split() tmpcoords[a,:] = [float(i) for i in tmp[1:]] if struct==0: atomic_symbols.append(tmp[0]) coords.append(tmpcoords) # Get energies f.readline() # line f.readline() #energy for struct in range(nstructs): self.energies[struct] = float(f.readline()) # Get grms f.readline() # max-force for struct in range(nstructs): grmss.append(float(f.readline())) # Get dE f.readline() for struct in range(nstructs): dE.append(float(f.readline())) # create newic object self.newic = Molecule.copy_from_options(self.nodes[0]) # initial energy self.nodes[0].V0 = self.nodes[0].energy self.nodes[0].gradrms=grmss[0] self.nodes[0].PES.dE = dE[0] self.nodes[-1].gradrms=grmss[-1] self.nodes[-1].PES.dE = dE[-1] self.emax = float(max(self.energies[1:-1])) self.TSnode = np.argmax(self.energies) print(" initial energy is %3.4f" % self.nodes[0].energy) for struct in range(1,nstructs-1): self.nodes[struct] = Molecule.copy_from_options(self.nodes[0],coords[struct],struct) self.nodes[struct].gradrms=grmss[struct] self.nodes[struct].PES.dE = dE[struct] self.nodes[struct].newHess=5 self.nnodes=self.nR=nstructs self.isRestarted=True self.done_growing=True self.nodes[self.TSnode].isTSnode=True print(" setting all interior nodes to active") for n in range(1,self.nnodes-1): self.active[n]=True self.optimizer[n].options['OPTTHRESH']=self.options['CONV_TOL']*2 self.optimizer[n].options['DMAX'] = 0.05 print(" V_profile: ", end=' ') for n in range(self.nnodes): print(" {:7.3f}".format(float(self.energies[n])), end=' ') print() print(" grms_profile: ", end=' ') for n in range(self.nnodes): print(" {:7.3f}".format(float(self.nodes[n].gradrms)), end=' ') print() print(" dE_profile: ", end=' ') for n in range(self.nnodes): print(" {:7.3f}".format(float(self.nodes[n].difference_energy)), end=' ') print() def go_gsm(self,max_iters=50,opt_steps=3,rtype=2): """ rtype=2 Find and Climb TS, 1 Climb with no exact find, 0 turning of climbing image and TS search """ self.set_V0() if not self.isRestarted: if self.growth_direction==0: self.interpolate(2) elif self.growth_direction==1: self.interpolateR(1) elif self.growth_direction==2: self.interpolateP(1) oi = self.growth_iters(iters=max_iters,maxopt=opt_steps) print("Done Growing the String!!!") self.write_xyz_files(iters=1,base='grown_string',nconstraints=1) self.done_growing = True print(" initial ic_reparam") self.get_tangents_1() self.ic_reparam(ic_reparam_steps=25) self.write_xyz_files(iters=1,base='initial_ic_reparam',nconstraints=1) else: oi=0 self.get_tangents_1() for i in range(self.nnodes): if self.nodes[i] !=None: self.optimizer[i].options['OPTTHRESH'] = self.options['CONV_TOL']*2 if self.tscontinue==True: if max_iters-oi>0: opt_iters=max_iters-oi self.opt_iters(max_iter=opt_iters,optsteps=opt_steps,rtype=rtype) else: print("Exiting early") print("Finished GSM!") def interpolate(self,newnodes=1): if self.nn+newnodes > self.nnodes: print("Adding too many nodes, cannot interpolate") sign = -1 for i in range(newnodes): sign *= -1 if sign == 1: self.interpolateR() else: self.interpolateP() def add_node(self,n1,n2,n3): print(" adding node: %i between %i %i from %i" %(n2,n1,n3,n1)) ictan,_ = self.tangent(n3,n1) Vecs = self.nodes[n1].update_coordinate_basis(constraints=ictan) dq0 = np.zeros((Vecs.shape[1],1)) dqmag = np.dot(Vecs[:,0],ictan) print(" dqmag: %1.3f"%dqmag) if self.nnodes-self.nn > 1: dq0[0] = -dqmag/float(self.nnodes-self.nn) else: dq0[0] = -dqmag/2.0; print(" dq0[constraint]: %1.3f" % dq0[0]) old_xyz = self.nodes[n1].xyz.copy() new_xyz = self.nodes[n1].coord_obj.newCartesian(old_xyz,dq0) new_node = Molecule.copy_from_options(self.nodes[n1],new_xyz,n2) return new_node def set_active(self,nR,nP): #print(" Here is active:",self.active) if nR!=nP and self.growth_direction==0: print((" setting active nodes to %i and %i"%(nR,nP))) elif self.growth_direction==1: print((" setting active node to %i "%nR)) elif self.growth_direction==2: print((" setting active node to %i "%nP)) else: print((" setting active node to %i "%nR)) for i in range(self.nnodes): if self.nodes[i] != None: self.optimizer[i].options['OPTTHRESH'] = self.options['CONV_TOL']*2. self.active[nR] = True self.active[nP] = True if self.growth_direction==1: self.active[nP]=False if self.growth_direction==2: self.active[nR]=False #print(" Here is new active:",self.active) def check_if_grown(self): isDone=False if self.nn==self.nnodes: isDone=True if self.growth_direction==1: print("need to add last node") raise NotImplementedError #TODO return isDone def check_add_node(self): success=True if self.nodes[self.nR-1].gradrms < self.gaddmax and self.growth_direction!=2: if self.nodes[self.nR] == None: self.interpolateR() if self.nodes[self.nnodes-self.nP].gradrms < self.gaddmax and self.growth_direction!=1: if self.nodes[-self.nP-1] == None: self.interpolateP() return success def tangent(self,n1,n2): #print(" getting tangent from between %i %i pointing towards %i"%(n2,n1,n2)) # this could have been done easier but it is nicer to do it this way Q1 = self.nodes[n1].primitive_internal_values Q2 = self.nodes[n2].primitive_internal_values PMDiff = Q2-Q1 #for i in range(len(PMDiff)): for k,prim in zip(list(range(len(PMDiff))),self.nodes[n1].primitive_internal_coordinates): if prim.isPeriodic: Plus2Pi = PMDiff[k] + 2*np.pi Minus2Pi = PMDiff[k] - 2*np.pi if np.abs(PMDiff[k]) > np.abs(Plus2Pi): PMDiff[k] = Plus2Pi if np.abs(PMDiff[k]) > np.abs(Minus2Pi): PMDiff[k] = Minus2Pi return np.reshape(PMDiff,(-1,1)),None def make_nlist(self): ncurrent = 0 nlist = [0]*(2*self.nnodes) for n in range(self.nR-1): nlist[2*ncurrent] = n nlist[2*ncurrent+1] = n+1 ncurrent += 1 for n in range(self.nnodes-self.nP+1,self.nnodes): nlist[2*ncurrent] = n nlist[2*ncurrent+1] = n-1 ncurrent += 1 nlist[2*ncurrent] = self.nR -1 nlist[2*ncurrent+1] = self.nnodes - self.nP if False: nlist[2*ncurrent+1] = self.nR - 2 #for isMAP_SE #TODO is this actually used? if self.nR == 0: nlist[2*ncurrent] += 1 if self.nP == 0: nlist[2*ncurrent+1] -= 1 ncurrent += 1 nlist[2*ncurrent] = self.nnodes -self.nP nlist[2*ncurrent+1] = self.nR-1 #TODO is this actually used? if self.nR == 0: nlist[2*ncurrent+1] += 1 if self.nP == 0: nlist[2*ncurrent] -= 1 ncurrent += 1 return ncurrent,nlist def check_opt(self,totalgrad,fp,rtype): isDone=False #if rtype==self.stage: # previously checked if rtype equals and 'stage' -- a previuos definition of climb/find were equal if True: if self.nodes[self.TSnode].gradrms<self.options['CONV_TOL'] and self.dE_iter<0.1: #TODO should check totalgrad isDone=True self.tscontinue=False if totalgrad<0.1 and self.nodes[self.TSnode].gradrms<2.5*self.options['CONV_TOL']: #TODO extra crit here isDone=True self.tscontinue=False return isDone def set_V0(self): self.nodes[0].V0 = self.nodes[0].energy #TODO should be actual gradient self.nodes[0].gradrms = 0. if self.growth_direction!=1: self.nodes[-1].gradrms = 0. print(" Energy of the end points are %4.3f, %4.3f" %(self.nodes[0].energy,self.nodes[-1].energy)) print(" relative E %4.3f, %4.3f" %(0.0,self.nodes[-1].energy-self.nodes[0].energy)) else: print(" Energy of end points are %4.3f " % self.nodes[0].energy) self.nodes[-1].energy = self.nodes[0].energy self.nodes[-1].gradrms = 0. if __name__=='__main__': from .qchem import QChem from .pes import PES from .dlc_new import DelocalizedInternalCoordinates from .eigenvector_follow import eigenvector_follow from ._linesearch import backtrack,NoLineSearch from .molecule import Molecule from .orca import Orca #basis="sto-3g" basis='6-31G' nproc=1 #functional='HF' functional='B3LYP' filepath1="examples/tests/butadiene_ethene.xyz" filepath2="examples/tests/cyclohexene.xyz" #filepath1='reactant.xyz' #filepath2='product.xyz' lot1= Orca.from_options(states=[(1,0)],charge=0,basis=basis,functional=functional,nproc=nproc,fnm=filepath1) lot2 = Orca(lot1.options.copy().set_values({'fnm':filepath2})) pes1 = PES.from_options(lot=lot1,ad_idx=0,multiplicity=1) pes2 = PES(pes1.options.copy().set_values({'lot':lot2})) M1 = Molecule.from_options(fnm=filepath1,PES=pes1,coordinate_type="DLC") M2 = Molecule.from_options(fnm=filepath2,PES=pes2,coordinate_type="DLC") optimizer=eigenvector_follow.from_options(print_level=1) #default parameters fine here/opt_type will get set by GSM gsm = GSM.from_options(reactant=M1,product=M2,nnodes=9,optimizer=optimizer,print_level=1) gsm.go_gsm(rtype=2,opt_steps=3)
[ "numpy.abs", "numpy.argmax", "numpy.zeros", "numpy.reshape", "numpy.dot" ]
[((3122, 3146), 'numpy.argmax', 'np.argmax', (['self.energies'], {}), '(self.energies)\n', (3131, 3146), True, 'import numpy as np\n'), ((6410, 6438), 'numpy.zeros', 'np.zeros', (['(Vecs.shape[1], 1)'], {}), '((Vecs.shape[1], 1))\n', (6418, 6438), True, 'import numpy as np\n'), ((6454, 6479), 'numpy.dot', 'np.dot', (['Vecs[:, 0]', 'ictan'], {}), '(Vecs[:, 0], ictan)\n', (6460, 6479), True, 'import numpy as np\n'), ((9279, 9306), 'numpy.reshape', 'np.reshape', (['PMDiff', '(-1, 1)'], {}), '(PMDiff, (-1, 1))\n', (9289, 9306), True, 'import numpy as np\n'), ((1833, 1854), 'numpy.zeros', 'np.zeros', (['(natoms, 3)'], {}), '((natoms, 3))\n', (1841, 1854), True, 'import numpy as np\n'), ((9089, 9106), 'numpy.abs', 'np.abs', (['PMDiff[k]'], {}), '(PMDiff[k])\n', (9095, 9106), True, 'import numpy as np\n'), ((9109, 9124), 'numpy.abs', 'np.abs', (['Plus2Pi'], {}), '(Plus2Pi)\n', (9115, 9124), True, 'import numpy as np\n'), ((9185, 9202), 'numpy.abs', 'np.abs', (['PMDiff[k]'], {}), '(PMDiff[k])\n', (9191, 9202), True, 'import numpy as np\n'), ((9205, 9221), 'numpy.abs', 'np.abs', (['Minus2Pi'], {}), '(Minus2Pi)\n', (9211, 9221), True, 'import numpy as np\n')]
import os from abc import abstractmethod from datetime import datetime import cv2 import numpy as np from bot import default_timestamp from bot.utils.data import load_dict_from_hdf5, save_dict_to_hdf5 class Predefined(object): _config = None dataset = None version = None assets = None def __init__(self, config, version): self._config = config self.cache_file = config.get('locations', 'cache_file') self.dataset = self.dataset or self.__class__.__name__ self.assets = config.get('locations', 'assets') self.version = version self.get_cache() self.check_cache() _cache = None _last_read = datetime.fromtimestamp(default_timestamp) @property def cache(self): return self._cache @cache.setter def cache(self, value): self._last_read = datetime.now() self._cache = value def check_cache(self): pass def get_cache(self): if not os.path.exists(self.cache_file): self.generate() if self.cache is None: self.cache = load_dict_from_hdf5(self.cache_file) if self.dataset in self.cache.keys(): return self.generate() _duel_varient = None @property def duel_variant(self): raise NotImplementedError("Class {} did not implement duel variant property".format(self.__class__.__name__)) _auto_duel = None @property def autoduel(self): raise NotImplementedError("Class {} did not implement auto duel property".format(self.__class__.__name__)) # TODO: IMPLEMENT METHOD TO DETERMINE THE ACCURACY OR THE LIKELHOOD THAT THIS IS AN AUTODUEL BUTTON def determine_autoduel_status(self, img): vals = self.cache.get(self.dataset) autodueloff = vals['auto_duel_off'] autoduelon = vals['auto_duel_on'] current = self.get_image_stats(img, **self.autoduel) dist1 = np.linalg.norm(current - autoduelon) dist2 = np.linalg.norm(current - autodueloff) if dist1 < dist2: return True return False def determine_duel_variant(self, img): vals = self.cache.get(self.dataset) ver_duel_variant = vals['duel_variant'] edges = cv2.Canny(img, 240, 255) current = Predefined.get_image_stats(edges, **self.duel_variant) dist1 = np.linalg.norm(current - ver_duel_variant) if dist1 <= 5: return True return False @staticmethod def get_image_stats(img, left=0, top=0, width=0, height=0): crop_img = img[top:(top + height), left:(left + width)] (means, stds) = cv2.meanStdDev(crop_img) stats = np.concatenate([means, stds]).flatten() return stats def write_hdf5(self, data, dataset): data = {dataset: data} save_dict_to_hdf5(data, self.cache_file, mode='a') @abstractmethod def generate(self): raise NotImplementedError("Class {} did not implement generate".format(self.__class__.__name__)) @property def street_replay_location(self): return 4 @property def quick_rankduel_location(self): return 2
[ "cv2.Canny", "bot.utils.data.load_dict_from_hdf5", "os.path.exists", "bot.utils.data.save_dict_to_hdf5", "numpy.linalg.norm", "cv2.meanStdDev", "datetime.datetime.fromtimestamp", "datetime.datetime.now", "numpy.concatenate" ]
[((680, 721), 'datetime.datetime.fromtimestamp', 'datetime.fromtimestamp', (['default_timestamp'], {}), '(default_timestamp)\n', (702, 721), False, 'from datetime import datetime\n'), ((858, 872), 'datetime.datetime.now', 'datetime.now', ([], {}), '()\n', (870, 872), False, 'from datetime import datetime\n'), ((1961, 1997), 'numpy.linalg.norm', 'np.linalg.norm', (['(current - autoduelon)'], {}), '(current - autoduelon)\n', (1975, 1997), True, 'import numpy as np\n'), ((2014, 2051), 'numpy.linalg.norm', 'np.linalg.norm', (['(current - autodueloff)'], {}), '(current - autodueloff)\n', (2028, 2051), True, 'import numpy as np\n'), ((2275, 2299), 'cv2.Canny', 'cv2.Canny', (['img', '(240)', '(255)'], {}), '(img, 240, 255)\n', (2284, 2299), False, 'import cv2\n'), ((2389, 2431), 'numpy.linalg.norm', 'np.linalg.norm', (['(current - ver_duel_variant)'], {}), '(current - ver_duel_variant)\n', (2403, 2431), True, 'import numpy as np\n'), ((2671, 2695), 'cv2.meanStdDev', 'cv2.meanStdDev', (['crop_img'], {}), '(crop_img)\n', (2685, 2695), False, 'import cv2\n'), ((2854, 2904), 'bot.utils.data.save_dict_to_hdf5', 'save_dict_to_hdf5', (['data', 'self.cache_file'], {'mode': '"""a"""'}), "(data, self.cache_file, mode='a')\n", (2871, 2904), False, 'from bot.utils.data import load_dict_from_hdf5, save_dict_to_hdf5\n'), ((983, 1014), 'os.path.exists', 'os.path.exists', (['self.cache_file'], {}), '(self.cache_file)\n', (997, 1014), False, 'import os\n'), ((1100, 1136), 'bot.utils.data.load_dict_from_hdf5', 'load_dict_from_hdf5', (['self.cache_file'], {}), '(self.cache_file)\n', (1119, 1136), False, 'from bot.utils.data import load_dict_from_hdf5, save_dict_to_hdf5\n'), ((2712, 2741), 'numpy.concatenate', 'np.concatenate', (['[means, stds]'], {}), '([means, stds])\n', (2726, 2741), True, 'import numpy as np\n')]
import json import numpy as np import DataStore as ds class ExperienceReplay(object): def __init__(self, max_memory=100, discount=.9, env = None, sequence_dim=(1,1)): self.max_memory = max_memory self.memory = list() self.discount = discount self.environment = env self.sequence_dim = sequence_dim def remember(self, states, game_over): # memory[i] = [[state_t, action_t, reward_t, state_t+1], game_over?] self.memory.append([states, game_over]) if len(self.memory) > self.max_memory: del self.memory[0] def get_batch(self, model, batch_size=10): len_memory = len(self.memory) num_actions = model.output_shape[-1] out_dim = self.environment.get_action_count() inputs = np.zeros((min(len_memory, batch_size),) + self.sequence_dim) targets = np.zeros((inputs.shape[0], num_actions)) for i, idx in enumerate(np.random.randint(0, len_memory, size=inputs.shape[0])): print("DIM ",i,idx,len_memory) #state_t, action_t, reward_t, state_tp1, idays_t, lineindex_t = self.memory[idx][0] action_t, reward_t, idays_t, lineindex_t = self.memory[idx][0] state_t = self.environment.observe(idays_t, lineindex_t) # State TP1 is the next state game_over = self.memory[idx][1] #print ("STATET",state_t) #inputs[i:i+1] = state_t inputs[i] = state_t # There should be no target values for actions not taken. # Thou shalt not correct actions not taken #deep a = model.predict(self.resize_input(state_t))[0] print("TARGET ",a) targets[i] = a if game_over: # if game_over is True targets[i, action_t] = reward_t else: state_tp1 = self.environment.observe(idays_t, lineindex_t+1) # reward_t + gamma * max_a' Q(s', a') Q_sa = np.max(model.predict(self.resize_input(state_tp1))[0]) targets[i, action_t] = reward_t + self.discount * Q_sa print("TARGET after",targets[i]) print ("INPUTS SHAPE after get_batch",inputs.shape) return inputs, targets def resize_input(self, i): """ resize input for ufcnn """ #return i.reshape((i.shape[0],i.shape[1],1)) # for Catch #print ("NET INPUT ",i) if i.ndim < 3: i = i.reshape((1,i.shape[0],i.shape[1])) return i
[ "numpy.random.randint", "numpy.zeros" ]
[((874, 914), 'numpy.zeros', 'np.zeros', (['(inputs.shape[0], num_actions)'], {}), '((inputs.shape[0], num_actions))\n', (882, 914), True, 'import numpy as np\n'), ((947, 1001), 'numpy.random.randint', 'np.random.randint', (['(0)', 'len_memory'], {'size': 'inputs.shape[0]'}), '(0, len_memory, size=inputs.shape[0])\n', (964, 1001), True, 'import numpy as np\n')]
# Date: 12/06/2019 # Author: <NAME> # System Class import numpy as np import copy import itertools import h5py import glob import os from tvtk.api import tvtk # python wrappers for the C++ vtk ecosystem import shutil import datetime import julian from .timestep import Timestep from .referenceframe import ReferenceFrame from .celestialbody import CelestialBody from .vessel import Vessel from .stage import Stage from ..helpermath.helpermath import * from ..forcetorque.gravity import gravity from ..forcetorque.thrust import thrust class System: """ System class. Args: name (str): System name. Used to create *_data folder. """ def __init__(self, name): self.name = name self.save_directory = self.name + '_data' self.current = Timestep() self.timesteps = {0 : self.current} self.dt = 0.1 self.endtime = 100.0 self.saveinterval = 1 self.scheme = 'euler' def save(self): """ Save system. """ # Create save file if it does not already exist if not(os.path.exists(self.name + '.psm')): open(self.name + '.psm', 'a').close() # Create save directory if it does not already exist if not(os.path.exists(self.save_directory)): os.mkdir(self.save_directory) path = self.save_directory + '/' + str(int(self.current.savefile)) + '.h5' f = h5py.File(path, 'a') # System class f.attrs.create('name', np.string_(self.name)) f.attrs.create('save_directory', np.string_(self.save_directory)) f.attrs.create('dt', self.dt) f.attrs.create('endtime', self.endtime) f.attrs.create('saveinterval', int(self.saveinterval)) self.current.save(f) f.close() def load(self, path, getAll=True): """ Load system data. Args: path (str): Path to *.psm file. getAll (bool): Load all data boolean. Default = True. """ # Reset timesteps dict self.setName(path[:-4]) self.save_directory = self.name + '_data' self.timesteps = {} # Load data into timesteps dict timestep_paths = glob.glob(self.save_directory + '/*.h5') if getAll: i = 0 for timestep_path in timestep_paths: f = h5py.File(timestep_path, 'r') new_timestep = Timestep() new_timestep.load(f) if i == len(timestep_paths): self.setDt(f.attrs['dt']) self.setEndTime(f.attrs['endtime']) self.setSaveInterval(f.attrs['saveinterval']) f.close() self.timesteps[new_timestep.savefile] = new_timestep i += 1 progress = (i / len(timestep_paths)) * 100 print("Load; Progress: " + str(np.around(progress, decimals = 2)) + " %.", end="\r") print('\n') else: timestep_path = timestep_paths[-1] f = h5py.File(timestep_path, 'r') new_timestep = Timestep() new_timestep.load(f) self.setDt(f.attrs['dt']) self.setEndTime(f.attrs['endtime']) self.setSaveInterval(f.attrs['saveinterval']) f.close() self.timesteps[new_timestep.time] = new_timestep # Set current timestep to the last one in timesteps dict self.setCurrent(self.timesteps[max(list(self.timesteps.keys()))]) def getName(self): """ Get system name. Returns: name (str): System name. """ return self.name def setName(self, name): """ Set system name. Args: name (str): System name. """ self.name = name def getCurrent(self): """ Get the System current Timestep. Returns: current (obj): System current Timestep. """ return self.current def setCurrent(self, timestep): """ Set the System current Timestep. Args: timestep (obj): Timestep to set System current timestep to. """ self.current = timestep def addTimestep(self, timestep): """ Add a Timestep to the system. Args: timestep (obj): Timestep object to add to system. """ self.timesteps[timestep.time] = timestep def getEndTime(self): """ Get system endtime. Returns: endtime (str): System endtime. """ return self.endtime def setEndTime(self, endtime): """ Set system end time [s]. Args: endtime (str): System endtime. """ self.endtime = endtime def getDt(self): """ Get timestep, dt [s]. Returns: dt (float): System dt. """ return self.dt def setDt(self, dt): """ Set timestep, dt [s]. Args: dt (float): System dt. """ self.dt = dt def getSaveInterval(self): """ Get saveinterval - every nth timestep. Returns: saveinterval (float): System saveinterval. """ return self.saveinterval def setSaveInterval(self, saveinterval): """ Set saveinterval - every nth timestep. Args: saveinterval (float): System saveinterval. """ self.saveinterval = saveinterval def setScheme(self, scheme): """ Set integration scheme to use for simulating the system. Args: scheme (str): Integration scheme to use ['euler', 'rk4']. """ self.scheme = scheme def getCelestialBodyInteractions(self): """ Get list of CelestialBody interactions. Returns: celestial_body_interactions (list): List of CelestialBody interactions. """ celestial_body_interactions = list(itertools.combinations(list(self.current.celestial_bodies.keys()), 2)) celestial_body_interactions = [list(celestial_body_interactions[i]) for i in range(0, len(celestial_body_interactions))] return celestial_body_interactions def getVesselsInteractions(self): """ Get list of Vessel interactions. Returns: vessels_interactions (list): List of Vessel interactions. """ celestial_bodies = list(self.current.celestial_bodies.keys()) vessels = list(self.current.vessels.keys()) vessels_interactions = [] for vessel in vessels: for celestial_body in celestial_bodies: vessels_interactions.append([celestial_body, vessel]) return vessels_interactions def simulateSystem(self): """ Simulate the system forward from current time. """ celestial_body_interactions = self.getCelestialBodyInteractions() vessels_interactions = self.getVesselsInteractions() iterations = int((self.endtime - self.current.time) / self.dt) for i in range(0, iterations): # Step 1: Calculate forces # Celestial Bodies: ## Gravity for interaction in celestial_body_interactions: obj0 = self.current.celestial_bodies[interaction[0]] obj1 = self.current.celestial_bodies[interaction[1]] gravityForce = gravity(obj0, obj1) obj0.addForce(-gravityForce) obj1.addForce(gravityForce) # Vessels: ## Gravity for interaction in vessels_interactions: obj0 = self.current.celestial_bodies[interaction[0]] obj1 = self.current.vessels[interaction[1]] gravityForce = gravity(obj0, obj1) obj1.addForce(gravityForce) # Step 2: Save data - included at this stage so that U is populated if i % self.saveinterval == 0: self.current.setSaveFile(int(i / self.saveinterval)) self.save() # Step 3: Simulate timestep if self.scheme == 'euler': # Celestial Bodies: for celestial_body in self.current.celestial_bodies.values(): celestial_body.simulate(self.dt, celestial_body.euler) # Vessels: for vessel in self.current.vessels.values(): vessel.simulate(self.dt, vessel.euler) elif self.scheme == 'rk4': # Celestial Bodies: for celestial_body in self.current.celestial_bodies.values(): celestial_body.simulate(self.dt, celestial_body.rk4) # Vessels: for vessel in self.current.vessels.values(): vessel.simulate(self.dt, vessel.rk4) # Step 4: Iterate on time self.current.setTime(self.current.time + self.dt) self.current.setDatetime(self.current.date_time + datetime.timedelta(0, self.dt)) progress = (i / iterations) * 100 print("Simulate System; Progress: " + str(np.around(progress, decimals = 2)) + " %.", end="\r") print('\n')
[ "os.mkdir", "h5py.File", "os.path.exists", "numpy.around", "datetime.timedelta", "numpy.string_", "glob.glob" ]
[((1426, 1446), 'h5py.File', 'h5py.File', (['path', '"""a"""'], {}), "(path, 'a')\n", (1435, 1446), False, 'import h5py\n'), ((2219, 2259), 'glob.glob', 'glob.glob', (["(self.save_directory + '/*.h5')"], {}), "(self.save_directory + '/*.h5')\n", (2228, 2259), False, 'import glob\n'), ((1088, 1122), 'os.path.exists', 'os.path.exists', (["(self.name + '.psm')"], {}), "(self.name + '.psm')\n", (1102, 1122), False, 'import os\n'), ((1251, 1286), 'os.path.exists', 'os.path.exists', (['self.save_directory'], {}), '(self.save_directory)\n', (1265, 1286), False, 'import os\n'), ((1301, 1330), 'os.mkdir', 'os.mkdir', (['self.save_directory'], {}), '(self.save_directory)\n', (1309, 1330), False, 'import os\n'), ((1501, 1522), 'numpy.string_', 'np.string_', (['self.name'], {}), '(self.name)\n', (1511, 1522), True, 'import numpy as np\n'), ((1565, 1596), 'numpy.string_', 'np.string_', (['self.save_directory'], {}), '(self.save_directory)\n', (1575, 1596), True, 'import numpy as np\n'), ((3067, 3096), 'h5py.File', 'h5py.File', (['timestep_path', '"""r"""'], {}), "(timestep_path, 'r')\n", (3076, 3096), False, 'import h5py\n'), ((2366, 2395), 'h5py.File', 'h5py.File', (['timestep_path', '"""r"""'], {}), "(timestep_path, 'r')\n", (2375, 2395), False, 'import h5py\n'), ((9163, 9193), 'datetime.timedelta', 'datetime.timedelta', (['(0)', 'self.dt'], {}), '(0, self.dt)\n', (9181, 9193), False, 'import datetime\n'), ((9295, 9326), 'numpy.around', 'np.around', (['progress'], {'decimals': '(2)'}), '(progress, decimals=2)\n', (9304, 9326), True, 'import numpy as np\n'), ((2912, 2943), 'numpy.around', 'np.around', (['progress'], {'decimals': '(2)'}), '(progress, decimals=2)\n', (2921, 2943), True, 'import numpy as np\n')]
# -*- coding: utf-8 -*- """ Low-level Python bindings to the Minpack library. This module forwards the CFFI generated bindings to the Minpack library and provides a Pythonic interface to the C API. """ import numpy as np import functools import math from typing import Optional from .typing import ( CallableHybrd, CallableHybrj, CallableLmder, CallableLmdif, CallableLmstr, ) from ._libminpack import ffi, lib from .exception import info_hy, info_lm class UserData: """ Carry Python callable object through callback and propagate exceptions without disturbing foreign runtime. """ def __init__(self, fcn, **kwargs): self.fcn = fcn self.exception = None self.kwargs = kwargs @ffi.def_extern() def func(n, x, fvec, iflag, data) -> None: """ Entry point for callback from minpack_hybrd and minpack_hybrd1 library functions. Restores type information for NDArray objects and calls the user-provided callback. """ if iflag[0] <= 0: return handle: UserData = ffi.from_handle(data) try: handle.fcn( np.frombuffer(ffi.buffer(x, n * real.itemsize), dtype=real), np.frombuffer(ffi.buffer(fvec, n * real.itemsize), dtype=real), **handle.kwargs, ) except BaseException as e: iflag[0] = -1 handle.exception = e @ffi.def_extern() def fcn_hybrj(n, x, fvec, fjac, ldfjac, iflag, data) -> None: """ Entry point for callback from minpack_hybrj and minpack_hybrj1 library functions. Restores type information for NDArray objects and calls the user-provided callback. """ if iflag[0] <= 0: return handle: UserData = ffi.from_handle(data) try: fjac = np.frombuffer(ffi.buffer(fjac, ldfjac * n * real.itemsize), dtype=real) handle.fcn( np.frombuffer(ffi.buffer(x, n * real.itemsize), dtype=real), np.frombuffer(ffi.buffer(fvec, n * real.itemsize), dtype=real), np.reshape(fjac, (n, ldfjac)), iflag[0] == 2, **handle.kwargs, ) except BaseException as e: iflag[0] = -1 handle.exception = e @ffi.def_extern() def fcn_lmder(m, n, x, fvec, fjac, ldfjac, iflag, data) -> None: """ Entry point for callback from minpack_lmder and minpack_lmder1 library functions. Restores type information for NDArray objects and calls the user-provided callback. """ if iflag[0] <= 0: return handle: UserData = ffi.from_handle(data) try: fjac = np.frombuffer(ffi.buffer(fjac, ldfjac * n * real.itemsize), dtype=real) handle.fcn( np.frombuffer(ffi.buffer(x, n * real.itemsize), dtype=real), np.frombuffer(ffi.buffer(fvec, m * real.itemsize), dtype=real), np.reshape(fjac, (n, ldfjac)), iflag[0] == 2, **handle.kwargs, ) except BaseException as e: iflag[0] = -1 handle.exception = e @ffi.def_extern() def func2(m, n, x, fvec, iflag, data) -> None: """ Entry point for callback from minpack_lmdif and minpack_lmdif1 library functions. Restores type information for NDArray objects and calls the user-provided callback. """ if iflag[0] <= 0: return handle: UserData = ffi.from_handle(data) try: handle.fcn( np.frombuffer(ffi.buffer(x, n * real.itemsize), dtype=real), np.frombuffer(ffi.buffer(fvec, m * real.itemsize), dtype=real), **handle.kwargs, ) except BaseException as e: iflag[0] = -1 handle.exception = e @ffi.def_extern() def fcn_lmstr(m, n, x, fvec, fjrow, iflag, data) -> None: """ Entry point for callback from minpack_lmstr and minpack_lmstr1 library functions. Restores type information for NDArray objects and calls the user-provided callback. """ if iflag[0] <= 0: return handle: UserData = ffi.from_handle(data) try: handle.fcn( np.frombuffer(ffi.buffer(x, n * real.itemsize), dtype=real), np.frombuffer(ffi.buffer(fvec, m * real.itemsize), dtype=real), np.frombuffer(ffi.buffer(fjrow, n * real.itemsize), dtype=real), iflag[0] - 2 if iflag[0] > 1 else None, **handle.kwargs, ) except BaseException as e: iflag[0] = -1 handle.exception = e def extern_python(dec): """ Meta-decorator to attach a CFFI extern "Python" callback to a decorator handling the Python side of the callback. """ def layer(*args, **kwargs): def wrapper(func): return dec(func, *args, **kwargs) return wrapper return layer @extern_python def cffi_callback(func, callback): """ Attach Python callback to a library function with extern "Python" callback. This decorator wraps the user-provided Python callback in a `UserData` object to carry it through the foreign runtime. It also propagates exceptions from the user-provided Python callback back through the foreign runtime and re-raises. """ @functools.wraps(func) def entry_point(fcn, *args, **kwargs): data = UserData(fcn, **kwargs) handle = ffi.new_handle(data) func(callback, *args, handle) if data.exception is not None: raise data.exception return entry_point real = np.dtype("f8") minpack_hybrd1 = cffi_callback(lib.func)(lib.minpack_hybrd1) minpack_hybrd = cffi_callback(lib.func)(lib.minpack_hybrd) minpack_hybrj1 = cffi_callback(lib.fcn_hybrj)(lib.minpack_hybrj1) minpack_hybrj = cffi_callback(lib.fcn_hybrj)(lib.minpack_hybrj) minpack_lmder1 = cffi_callback(lib.fcn_lmder)(lib.minpack_lmder1) minpack_lmder = cffi_callback(lib.fcn_lmder)(lib.minpack_lmder) minpack_lmdif1 = cffi_callback(lib.func2)(lib.minpack_lmdif1) minpack_lmdif = cffi_callback(lib.func2)(lib.minpack_lmdif) minpack_lmstr1 = cffi_callback(lib.fcn_lmstr)(lib.minpack_lmstr1) minpack_lmstr = cffi_callback(lib.fcn_lmstr)(lib.minpack_lmstr) minpack_chkder = lib.minpack_chkder def hybrd1( fcn: CallableHybrd, x: np.ndarray, fvec: np.ndarray, tol: float = math.sqrt(np.finfo(real).eps), **kwargs, ) -> int: """ Find a zero of a system of n nonlinear functions in n variables by a modification of the Powell hybrid method. This is done by using the more general nonlinear equation solver `hybrd`. The user must provide a subroutine which calculates the functions. The Jacobian is then calculated by a forward-difference approximation. Parameters ---------- func : callable ``f(x, fvec)`` A function that takes at least one (possibly vector) argument, and returns a value of the same length. x : ndarray The starting estimate for the roots of ``func(x) = 0``. fvec: ndarray Function evaluated at the output tol : float The calculation will terminate if the relative error between two consecutive iterates is at most `tol`. Returns ------- info : int Set to 1 if a solution was found. Raises ------ MinpackInputError In case of invalid input parameters. MinpackMaxIterations When the maximum number of iterations is exceeded. MinpackFunctionTolerance When the function tolerance cannot be satisfied. MinpackSlowProgressJacobian When the Jacobian is not changing. MinpackSlowProgress When the function is not changing. Examples -------- >>> import numpy as np >>> from minpack import hybrd >>> >>> def fcn(x, fvec) -> None: ... fvec[0] = x[0] * np.cos(x[1]) - 4 ... fvec[1] = x[1] * x[0] - x[1] - 5 ... >>> x = np.array(2 * [1.0]) >>> fvec = np.zeros(2, dtype=np.float64) >>> hybrd1(fcn, x, fvec) 1 >>> x array([6.50409711, 0.90841421]) >>> np.isclose(fvec, [0.0, 0.0]) # fvec should be almost 0.0. array([ True, True]) """ n = x.size lwa = n * (3 * n + 13) // 2 wa = np.zeros(lwa, dtype=real) info = ffi.new("int *") minpack_hybrd1( fcn, n, ffi.cast("double*", x.ctypes.data), ffi.cast("double*", fvec.ctypes.data), tol, info, ffi.cast("double*", wa.ctypes.data), lwa, **kwargs, ) ex = info_hy(info[0]) if ex is not None: raise ex(ex.__doc__) return info[0] def hybrd( fcn: CallableHybrd, x: np.ndarray, fvec: np.ndarray, xtol: float = math.sqrt(np.finfo(real).eps), *, maxfev: Optional[int] = None, ml: Optional[int] = None, mu: Optional[int] = None, epsfcn: float = 0.0, diag: Optional[np.ndarray] = None, mode: int = 2, factor: float = 100.0, nprint: int = 0, fjac: Optional[np.ndarray] = None, r: Optional[np.ndarray] = None, qtf: Optional[np.ndarray] = None, **kwargs, ) -> int: """ Find a zero of a system of n nonlinear functions in n variables by a modification of the Powell hybrid method. The user must provide a subroutine which calculates the functions. The Jacobian is then calculated by a forward-difference approximation. Raises ------ MinpackInputError In case of invalid input parameters. MinpackMaxIterations When the maximum number of iterations is exceeded. MinpackFunctionTolerance When the function tolerance cannot be satisfied. MinpackSlowProgressJacobian When the Jacobian is not changing. MinpackSlowProgress When the function is not changing. """ n = x.size info = ffi.new("int *") nfev = ffi.new("int *") if maxfev is None: maxfev = 200 * (n + 1) if ml is None: ml = n - 1 if mu is None: mu = n - 1 if diag is None: diag = np.ones(n, dtype=real) if fjac is None: fjac = np.zeros((n, n), dtype=real) if r is None: r = np.zeros(n * (n + 1) // 2, dtype=real) if qtf is None: qtf = np.zeros(n, dtype=real) wa1 = np.zeros(n, dtype=real) wa2 = np.zeros(n, dtype=real) wa3 = np.zeros(n, dtype=real) wa4 = np.zeros(n, dtype=real) minpack_hybrd( fcn, n, ffi.cast("double*", x.ctypes.data), ffi.cast("double*", fvec.ctypes.data), xtol, maxfev, ml, mu, epsfcn, ffi.cast("double*", diag.ctypes.data), mode, factor, nprint, info, nfev, ffi.cast("double*", fjac.ctypes.data), n, ffi.cast("double*", r.ctypes.data), r.size, ffi.cast("double*", qtf.ctypes.data), ffi.cast("double*", wa1.ctypes.data), ffi.cast("double*", wa2.ctypes.data), ffi.cast("double*", wa3.ctypes.data), ffi.cast("double*", wa4.ctypes.data), **kwargs, ) ex = info_hy(info[0]) if ex is not None: raise ex(ex.__doc__) return info[0] def hybrj1( fcn: CallableHybrj, x: np.ndarray, fvec: np.ndarray, fjac: np.ndarray, tol: float = math.sqrt(np.finfo(real).eps), **kwargs, ) -> int: """ Find a zero of a system of n nonlinear functions in n variables by a modification of the Powell hybrid method. This is done by using the more general nonlinear equation solver `hybrj`. The user must provide a subroutine which calculates the functions and the Jacobian. Raises ------ MinpackInputError In case of invalid input parameters. MinpackMaxIterations When the maximum number of iterations is exceeded. MinpackFunctionTolerance When the function tolerance cannot be satisfied. MinpackSlowProgressJacobian When the Jacobian is not changing. MinpackSlowProgress When the function is not changing. """ n = x.size lwa = (n * (n + 13)) // 2 wa = np.zeros(lwa, dtype=real) info = ffi.new("int *") minpack_hybrj1( fcn, n, ffi.cast("double*", x.ctypes.data), ffi.cast("double*", fvec.ctypes.data), ffi.cast("double*", fjac.ctypes.data), n, tol, info, ffi.cast("double*", wa.ctypes.data), lwa, **kwargs, ) ex = info_hy(info[0]) if ex is not None: raise ex(ex.__doc__) return info[0] def hybrj( fcn: CallableHybrj, x: np.ndarray, fvec: np.ndarray, fjac: np.ndarray, xtol: float = math.sqrt(np.finfo(real).eps), *, maxfev: Optional[int] = None, diag: Optional[np.ndarray] = None, mode: int = 2, factor: float = 100.0, nprint: int = 0, r: Optional[np.ndarray] = None, qtf: Optional[np.ndarray] = None, **kwargs, ) -> int: """ Find a zero of a system of n nonlinear functions in n variables by a modification of the Powell hybrid method. The user must provide a subroutine which calculates the functions and the Jacobian. Raises ------ MinpackInputError In case of invalid input parameters. MinpackMaxIterations When the maximum number of iterations is exceeded. MinpackFunctionTolerance When the function tolerance cannot be satisfied. MinpackSlowProgressJacobian When the Jacobian is not changing. MinpackSlowProgress When the function is not changing. """ n = x.size info = ffi.new("int *") nfev = ffi.new("int *") njev = ffi.new("int *") if maxfev is None: maxfev = 200 * (n + 1) if diag is None: diag = np.ones(n, dtype=real) if fjac is None: fjac = np.zeros((n, n), dtype=real) if r is None: r = np.zeros(n * (n + 1) // 2, dtype=real) if qtf is None: qtf = np.zeros(n, dtype=real) wa1 = np.zeros(n, dtype=real) wa2 = np.zeros(n, dtype=real) wa3 = np.zeros(n, dtype=real) wa4 = np.zeros(n, dtype=real) minpack_hybrj( fcn, n, ffi.cast("double*", x.ctypes.data), ffi.cast("double*", fvec.ctypes.data), ffi.cast("double*", fjac.ctypes.data), n, xtol, maxfev, ffi.cast("double*", diag.ctypes.data), mode, factor, nprint, info, nfev, njev, ffi.cast("double*", r.ctypes.data), r.size, ffi.cast("double*", qtf.ctypes.data), ffi.cast("double*", wa1.ctypes.data), ffi.cast("double*", wa2.ctypes.data), ffi.cast("double*", wa3.ctypes.data), ffi.cast("double*", wa4.ctypes.data), **kwargs, ) ex = info_hy(info[0]) if ex is not None: raise ex(ex.__doc__) return info[0] def lmder1( fcn: CallableLmder, x: np.ndarray, fvec: np.ndarray, fjac: np.ndarray, tol: float = math.sqrt(np.finfo(real).eps), **kwargs, ) -> int: """ Minimize the sum of the squares of m nonlinear functions in n variables by a modification of the Levenberg-Marquardt algorithm. This is done by using the more general least-squares solver `lmder`. The user must provide a subroutine which calculates the functions and the Jacobian. Raises ------ MinpackInputError In case of invalid input parameters. MinpackMaxIterations When the maximum number of iterations is exceeded. MinpackFunctionTolerance When the function tolerance cannot be satisfied. MinpackSolutionTolerance When no further improvement in the approximate solution is possible. MinpackJacobianTolerance The solution is orthogonal to the jacobian. """ n = x.size m = fvec.size lwa = 5 * n + m wa = np.zeros(lwa, dtype=real) ipvt = np.zeros(n, dtype=np.int32) info = ffi.new("int *") minpack_lmder1( fcn, m, n, ffi.cast("double*", x.ctypes.data), ffi.cast("double*", fvec.ctypes.data), ffi.cast("double*", fjac.ctypes.data), m, tol, info, ffi.cast("int*", ipvt.ctypes.data), ffi.cast("double*", wa.ctypes.data), lwa, **kwargs, ) ex = info_lm(info[0]) if ex is not None: raise ex(ex.__doc__) return info[0] def lmder( fcn: CallableLmder, x: np.ndarray, fvec: np.ndarray, fjac: np.ndarray, ftol: float = math.sqrt(np.finfo(real).eps), xtol: float = math.sqrt(np.finfo(real).eps), *, gtol: float = 0.0, maxfev: Optional[int] = None, diag: Optional[np.ndarray] = None, mode: int = 1, factor=100.0, nprint=0, ipvt: Optional[np.ndarray] = None, qtf: Optional[np.ndarray] = None, **kwargs, ) -> int: """ Minimize the sum of the squares of m nonlinear functions in n variables by a modification of the Levenberg-Marquardt algorithm. The user must provide a subroutine which calculates the functions and the Jacobian. Raises ------ MinpackInputError In case of invalid input parameters. MinpackMaxIterations When the maximum number of iterations is exceeded. MinpackFunctionTolerance When the function tolerance cannot be satisfied. MinpackSolutionTolerance When no further improvement in the approximate solution is possible. MinpackJacobianTolerance The solution is orthogonal to the jacobian. """ n = x.size m = fvec.size info = ffi.new("int *") nfev = ffi.new("int *") njev = ffi.new("int *") if diag is None: diag = np.ones(n, dtype=real) if maxfev is None: maxfev = 100 * (n + 1) if ipvt is None: ipvt = np.zeros(n, dtype=np.int32) if qtf is None: qtf = np.zeros(n, dtype=real) wa1 = np.zeros(n, dtype=real) wa2 = np.zeros(n, dtype=real) wa3 = np.zeros(n, dtype=real) wa4 = np.zeros(m, dtype=real) minpack_lmder( fcn, m, n, ffi.cast("double*", x.ctypes.data), ffi.cast("double*", fvec.ctypes.data), ffi.cast("double*", fjac.ctypes.data), m, ftol, xtol, gtol, maxfev, ffi.cast("double*", diag.ctypes.data), mode, factor, nprint, info, nfev, njev, ffi.cast("int*", ipvt.ctypes.data), ffi.cast("double*", qtf.ctypes.data), ffi.cast("double*", wa1.ctypes.data), ffi.cast("double*", wa2.ctypes.data), ffi.cast("double*", wa3.ctypes.data), ffi.cast("double*", wa4.ctypes.data), **kwargs, ) ex = info_lm(info[0]) if ex is not None: raise ex(ex.__doc__) return info[0] def lmdif1( fcn: CallableLmdif, x: np.ndarray, fvec: np.ndarray, tol: float = math.sqrt(np.finfo(real).eps), **kwargs, ) -> int: """ Minimize the sum of the squares of m nonlinear functions in n variables by a modification of the Levenberg-Marquardt algorithm. This is done by using the more general least-squares solver `lmdif`. The user must provide a subroutine which calculates the functions. The jacobian is then calculated by a forward-difference approximation. Parameters ---------- func : callable ``f(x, fvec)`` Should take at least one (possibly length n vector) argument and compute m floating point numbers in fvec. It must not return NaNs or fitting might fail. m must be greater than or equal to n. x : ndarray The starting estimate for the minimization. fvec : ndarray The function evaluated at the output. tol : float, optional Relative error desired in the sum of squares and the approximate solution. Returns ------- info : int An integer flag. If it is equal to 1, 2, 3 or 4, the solution was found. Otherwise, the solution was not found. Raises ------ MinpackInputError In case of invalid input parameters. MinpackMaxIterations When the maximum number of iterations is exceeded. MinpackFunctionTolerance When the function tolerance cannot be satisfied. MinpackSolutionTolerance When no further improvement in the approximate solution is possible. MinpackJacobianTolerance The solution is orthogonal to the jacobian. Example ------- >>> import numpy as np >>> from minpack import lmdif1 >>> >>> def func(x, fvec): ... fvec[:] = 2*(x-3)**2+1 ... >>> x = np.array(0.0) >>> fvec = np.zeros(1, dtype=np.float64) >>> lmdif1(func, x, fvec) 1 >>> x array(2.99999999) """ n = x.size m = fvec.size lwa = m * n + 5 * n + m wa = np.zeros(lwa, dtype=real) ipvt = np.zeros(n, dtype=np.int32) info = ffi.new("int *") minpack_lmdif1( fcn, m, n, ffi.cast("double*", x.ctypes.data), ffi.cast("double*", fvec.ctypes.data), tol, info, ffi.cast("int*", ipvt.ctypes.data), ffi.cast("double*", wa.ctypes.data), lwa, **kwargs, ) ex = info_lm(info[0]) if ex is not None: raise ex(ex.__doc__) return info[0] def lmdif( fcn: CallableLmdif, x: np.ndarray, fvec: np.ndarray, ftol: float = math.sqrt(np.finfo(real).eps), xtol: float = math.sqrt(np.finfo(real).eps), *, gtol: float = 0.0, maxfev: Optional[int] = None, epsfcn: float = 0.0, diag: Optional[np.ndarray] = None, mode=1, factor: float = 100.0, nprint: int = 0, fjac: Optional[np.ndarray] = None, ipvt: Optional[np.ndarray] = None, qtf: Optional[np.ndarray] = None, **kwargs, ) -> int: """ Minimize the sum of the squares of m nonlinear functions in n variables by a modification of the Levenberg-Marquardt algorithm. The user must provide a subroutine which calculates the functions. The jacobian is then calculated by a forward-difference approximation. Raises ------ MinpackInputError In case of invalid input parameters. MinpackMaxIterations When the maximum number of iterations is exceeded. MinpackFunctionTolerance When the function tolerance cannot be satisfied. MinpackSolutionTolerance When no further improvement in the approximate solution is possible. MinpackJacobianTolerance The solution is orthogonal to the jacobian. """ n = x.size m = fvec.size info = ffi.new("int *") nfev = ffi.new("int *") if maxfev is None: maxfev = 200 * (n + 1) if diag is None: diag = np.ones(n, dtype=real) if fjac is None: fjac = np.zeros((n, m), dtype=real) if ipvt is None: ipvt = np.zeros(n, dtype=np.int32) if qtf is None: qtf = np.zeros(n, dtype=real) wa1 = np.zeros(n, dtype=real) wa2 = np.zeros(n, dtype=real) wa3 = np.zeros(n, dtype=real) wa4 = np.zeros(m, dtype=real) minpack_lmdif( fcn, m, n, ffi.cast("double*", x.ctypes.data), ffi.cast("double*", fvec.ctypes.data), ftol, xtol, gtol, maxfev, epsfcn, ffi.cast("double*", diag.ctypes.data), mode, factor, nprint, info, nfev, ffi.cast("double*", fjac.ctypes.data), m, ffi.cast("int*", ipvt.ctypes.data), ffi.cast("double*", qtf.ctypes.data), ffi.cast("double*", wa1.ctypes.data), ffi.cast("double*", wa2.ctypes.data), ffi.cast("double*", wa3.ctypes.data), ffi.cast("double*", wa4.ctypes.data), **kwargs, ) ex = info_lm(info[0]) if ex is not None: raise ex(ex.__doc__) return info[0] def lmstr1( fcn: CallableLmstr, x: np.ndarray, fvec: np.ndarray, fjac: np.ndarray, tol: float = math.sqrt(np.finfo(real).eps), **kwargs, ) -> int: """ Minimize the sum of the squares of m nonlinear functions in n variables by a modification of the Levenberg-Marquardt algorithm which uses minimal storage. This is done by using the more general least-squares solver `lmstr`. The user must provide a subroutine which calculates the functions and the rows of the Jacobian. Raises ------ MinpackInputError In case of invalid input parameters. MinpackMaxIterations When the maximum number of iterations is exceeded. MinpackFunctionTolerance When the function tolerance cannot be satisfied. MinpackSolutionTolerance When no further improvement in the approximate solution is possible. MinpackJacobianTolerance The solution is orthogonal to the jacobian. """ n = x.size m = fvec.size lwa = m * n + 5 * n + m wa = np.zeros(lwa, dtype=real) ipvt = np.zeros(n, dtype=np.int32) info = ffi.new("int *") minpack_lmstr1( fcn, m, n, ffi.cast("double*", x.ctypes.data), ffi.cast("double*", fvec.ctypes.data), ffi.cast("double*", fjac.ctypes.data), n, tol, info, ffi.cast("int*", ipvt.ctypes.data), ffi.cast("double*", wa.ctypes.data), lwa, **kwargs, ) ex = info_lm(info[0]) if ex is not None: raise ex(ex.__doc__) return info[0] def lmstr( fcn: CallableLmstr, x: np.ndarray, fvec: np.ndarray, fjac: np.ndarray, ftol: float = math.sqrt(np.finfo(real).eps), xtol: float = math.sqrt(np.finfo(real).eps), *, gtol: float = 0.0, maxfev: Optional[int] = None, diag: Optional[np.ndarray] = None, mode: int = 1, factor: float = 100.0, nprint=0, ipvt: Optional[np.ndarray] = None, qtf: Optional[np.ndarray] = None, **kwargs, ) -> int: """ Minimize the sum of the squares of m nonlinear functions in n variables by a modification of the Levenberg-Marquardt algorithm which uses minimal storage. The user must provide a subroutine which calculates the functions and the rows of the Jacobian. Raises ------ MinpackInputError In case of invalid input parameters. MinpackMaxIterations When the maximum number of iterations is exceeded. MinpackFunctionTolerance When the function tolerance cannot be satisfied. MinpackSolutionTolerance When no further improvement in the approximate solution is possible. MinpackJacobianTolerance The solution is orthogonal to the jacobian. """ n = x.size m = fvec.size info = ffi.new("int *") nfev = ffi.new("int *") njev = ffi.new("int *") if maxfev is None: maxfev = 100 * (n + 1) if diag is None: diag = np.ones(n, dtype=real) if ipvt is None: ipvt = np.zeros(n, dtype=np.int32) if qtf is None: qtf = np.zeros(n, dtype=real) wa1 = np.zeros(n, dtype=real) wa2 = np.zeros(n, dtype=real) wa3 = np.zeros(n, dtype=real) wa4 = np.zeros(m, dtype=real) minpack_lmstr( fcn, m, n, ffi.cast("double*", x.ctypes.data), ffi.cast("double*", fvec.ctypes.data), ffi.cast("double*", fjac.ctypes.data), n, ftol, xtol, gtol, maxfev, ffi.cast("double*", diag.ctypes.data), mode, factor, nprint, info, nfev, njev, ffi.cast("int*", ipvt.ctypes.data), ffi.cast("double*", qtf.ctypes.data), ffi.cast("double*", wa1.ctypes.data), ffi.cast("double*", wa2.ctypes.data), ffi.cast("double*", wa3.ctypes.data), ffi.cast("double*", wa4.ctypes.data), **kwargs, ) ex = info_lm(info[0]) if ex is not None: raise ex(ex.__doc__) return info[0] def chkder(x, fvec, fjac, xp, fvecp, check, error): """ This subroutine checks the gradients of m nonlinear functions in n variables, evaluated at a point x, for consistency with the functions themselves. The subroutine does not perform reliably if cancellation or rounding errors cause a severe loss of significance in the evaluation of a function. Therefore, none of the components of x should be unusually small (in particular, zero) or any other value which may cause loss of significance. """ if not fvec.size == fjac.shape[-1] == fvecp.size == error.size: raise ValueError("fvec, fjac, fvecp, error must have the same size") if not x.size == fjac.shape[0] == xp.size: raise ValueError("x, fjac, xp must have the same size") m = fvec.size n = x.size ldfjac = fjac.shape[-1] minpack_chkder( m, n, ffi.cast("double*", x.ctypes.data), ffi.cast("double*", fvec.ctypes.data), ffi.cast("double*", fjac.ctypes.data), ldfjac, ffi.cast("double*", xp.ctypes.data), ffi.cast("double*", fvecp.ctypes.data), 2 if check else 1, ffi.cast("double*", error.ctypes.data), )
[ "numpy.dtype", "numpy.zeros", "numpy.ones", "numpy.finfo", "numpy.reshape", "functools.wraps" ]
[((5418, 5432), 'numpy.dtype', 'np.dtype', (['"""f8"""'], {}), "('f8')\n", (5426, 5432), True, 'import numpy as np\n'), ((5133, 5154), 'functools.wraps', 'functools.wraps', (['func'], {}), '(func)\n', (5148, 5154), False, 'import functools\n'), ((8091, 8116), 'numpy.zeros', 'np.zeros', (['lwa'], {'dtype': 'real'}), '(lwa, dtype=real)\n', (8099, 8116), True, 'import numpy as np\n'), ((10128, 10151), 'numpy.zeros', 'np.zeros', (['n'], {'dtype': 'real'}), '(n, dtype=real)\n', (10136, 10151), True, 'import numpy as np\n'), ((10162, 10185), 'numpy.zeros', 'np.zeros', (['n'], {'dtype': 'real'}), '(n, dtype=real)\n', (10170, 10185), True, 'import numpy as np\n'), ((10196, 10219), 'numpy.zeros', 'np.zeros', (['n'], {'dtype': 'real'}), '(n, dtype=real)\n', (10204, 10219), True, 'import numpy as np\n'), ((10230, 10253), 'numpy.zeros', 'np.zeros', (['n'], {'dtype': 'real'}), '(n, dtype=real)\n', (10238, 10253), True, 'import numpy as np\n'), ((11983, 12008), 'numpy.zeros', 'np.zeros', (['lwa'], {'dtype': 'real'}), '(lwa, dtype=real)\n', (11991, 12008), True, 'import numpy as np\n'), ((13874, 13897), 'numpy.zeros', 'np.zeros', (['n'], {'dtype': 'real'}), '(n, dtype=real)\n', (13882, 13897), True, 'import numpy as np\n'), ((13908, 13931), 'numpy.zeros', 'np.zeros', (['n'], {'dtype': 'real'}), '(n, dtype=real)\n', (13916, 13931), True, 'import numpy as np\n'), ((13942, 13965), 'numpy.zeros', 'np.zeros', (['n'], {'dtype': 'real'}), '(n, dtype=real)\n', (13950, 13965), True, 'import numpy as np\n'), ((13976, 13999), 'numpy.zeros', 'np.zeros', (['n'], {'dtype': 'real'}), '(n, dtype=real)\n', (13984, 13999), True, 'import numpy as np\n'), ((15764, 15789), 'numpy.zeros', 'np.zeros', (['lwa'], {'dtype': 'real'}), '(lwa, dtype=real)\n', (15772, 15789), True, 'import numpy as np\n'), ((15801, 15828), 'numpy.zeros', 'np.zeros', (['n'], {'dtype': 'np.int32'}), '(n, dtype=np.int32)\n', (15809, 15828), True, 'import numpy as np\n'), ((17814, 17837), 'numpy.zeros', 'np.zeros', (['n'], {'dtype': 'real'}), '(n, dtype=real)\n', (17822, 17837), True, 'import numpy as np\n'), ((17848, 17871), 'numpy.zeros', 'np.zeros', (['n'], {'dtype': 'real'}), '(n, dtype=real)\n', (17856, 17871), True, 'import numpy as np\n'), ((17882, 17905), 'numpy.zeros', 'np.zeros', (['n'], {'dtype': 'real'}), '(n, dtype=real)\n', (17890, 17905), True, 'import numpy as np\n'), ((17916, 17939), 'numpy.zeros', 'np.zeros', (['m'], {'dtype': 'real'}), '(m, dtype=real)\n', (17924, 17939), True, 'import numpy as np\n'), ((20767, 20792), 'numpy.zeros', 'np.zeros', (['lwa'], {'dtype': 'real'}), '(lwa, dtype=real)\n', (20775, 20792), True, 'import numpy as np\n'), ((20804, 20831), 'numpy.zeros', 'np.zeros', (['n'], {'dtype': 'np.int32'}), '(n, dtype=np.int32)\n', (20812, 20831), True, 'import numpy as np\n'), ((22905, 22928), 'numpy.zeros', 'np.zeros', (['n'], {'dtype': 'real'}), '(n, dtype=real)\n', (22913, 22928), True, 'import numpy as np\n'), ((22939, 22962), 'numpy.zeros', 'np.zeros', (['n'], {'dtype': 'real'}), '(n, dtype=real)\n', (22947, 22962), True, 'import numpy as np\n'), ((22973, 22996), 'numpy.zeros', 'np.zeros', (['n'], {'dtype': 'real'}), '(n, dtype=real)\n', (22981, 22996), True, 'import numpy as np\n'), ((23007, 23030), 'numpy.zeros', 'np.zeros', (['m'], {'dtype': 'real'}), '(m, dtype=real)\n', (23015, 23030), True, 'import numpy as np\n'), ((24871, 24896), 'numpy.zeros', 'np.zeros', (['lwa'], {'dtype': 'real'}), '(lwa, dtype=real)\n', (24879, 24896), True, 'import numpy as np\n'), ((24908, 24935), 'numpy.zeros', 'np.zeros', (['n'], {'dtype': 'np.int32'}), '(n, dtype=np.int32)\n', (24916, 24935), True, 'import numpy as np\n'), ((26973, 26996), 'numpy.zeros', 'np.zeros', (['n'], {'dtype': 'real'}), '(n, dtype=real)\n', (26981, 26996), True, 'import numpy as np\n'), ((27007, 27030), 'numpy.zeros', 'np.zeros', (['n'], {'dtype': 'real'}), '(n, dtype=real)\n', (27015, 27030), True, 'import numpy as np\n'), ((27041, 27064), 'numpy.zeros', 'np.zeros', (['n'], {'dtype': 'real'}), '(n, dtype=real)\n', (27049, 27064), True, 'import numpy as np\n'), ((27075, 27098), 'numpy.zeros', 'np.zeros', (['m'], {'dtype': 'real'}), '(m, dtype=real)\n', (27083, 27098), True, 'import numpy as np\n'), ((9903, 9925), 'numpy.ones', 'np.ones', (['n'], {'dtype': 'real'}), '(n, dtype=real)\n', (9910, 9925), True, 'import numpy as np\n'), ((9962, 9990), 'numpy.zeros', 'np.zeros', (['(n, n)'], {'dtype': 'real'}), '((n, n), dtype=real)\n', (9970, 9990), True, 'import numpy as np\n'), ((10021, 10059), 'numpy.zeros', 'np.zeros', (['(n * (n + 1) // 2)'], {'dtype': 'real'}), '(n * (n + 1) // 2, dtype=real)\n', (10029, 10059), True, 'import numpy as np\n'), ((10094, 10117), 'numpy.zeros', 'np.zeros', (['n'], {'dtype': 'real'}), '(n, dtype=real)\n', (10102, 10117), True, 'import numpy as np\n'), ((13649, 13671), 'numpy.ones', 'np.ones', (['n'], {'dtype': 'real'}), '(n, dtype=real)\n', (13656, 13671), True, 'import numpy as np\n'), ((13708, 13736), 'numpy.zeros', 'np.zeros', (['(n, n)'], {'dtype': 'real'}), '((n, n), dtype=real)\n', (13716, 13736), True, 'import numpy as np\n'), ((13767, 13805), 'numpy.zeros', 'np.zeros', (['(n * (n + 1) // 2)'], {'dtype': 'real'}), '(n * (n + 1) // 2, dtype=real)\n', (13775, 13805), True, 'import numpy as np\n'), ((13840, 13863), 'numpy.zeros', 'np.zeros', (['n'], {'dtype': 'real'}), '(n, dtype=real)\n', (13848, 13863), True, 'import numpy as np\n'), ((17605, 17627), 'numpy.ones', 'np.ones', (['n'], {'dtype': 'real'}), '(n, dtype=real)\n', (17612, 17627), True, 'import numpy as np\n'), ((17718, 17745), 'numpy.zeros', 'np.zeros', (['n'], {'dtype': 'np.int32'}), '(n, dtype=np.int32)\n', (17726, 17745), True, 'import numpy as np\n'), ((17780, 17803), 'numpy.zeros', 'np.zeros', (['n'], {'dtype': 'real'}), '(n, dtype=real)\n', (17788, 17803), True, 'import numpy as np\n'), ((22685, 22707), 'numpy.ones', 'np.ones', (['n'], {'dtype': 'real'}), '(n, dtype=real)\n', (22692, 22707), True, 'import numpy as np\n'), ((22744, 22772), 'numpy.zeros', 'np.zeros', (['(n, m)'], {'dtype': 'real'}), '((n, m), dtype=real)\n', (22752, 22772), True, 'import numpy as np\n'), ((22809, 22836), 'numpy.zeros', 'np.zeros', (['n'], {'dtype': 'np.int32'}), '(n, dtype=np.int32)\n', (22817, 22836), True, 'import numpy as np\n'), ((22871, 22894), 'numpy.zeros', 'np.zeros', (['n'], {'dtype': 'real'}), '(n, dtype=real)\n', (22879, 22894), True, 'import numpy as np\n'), ((26818, 26840), 'numpy.ones', 'np.ones', (['n'], {'dtype': 'real'}), '(n, dtype=real)\n', (26825, 26840), True, 'import numpy as np\n'), ((26877, 26904), 'numpy.zeros', 'np.zeros', (['n'], {'dtype': 'np.int32'}), '(n, dtype=np.int32)\n', (26885, 26904), True, 'import numpy as np\n'), ((26939, 26962), 'numpy.zeros', 'np.zeros', (['n'], {'dtype': 'real'}), '(n, dtype=real)\n', (26947, 26962), True, 'import numpy as np\n'), ((2010, 2039), 'numpy.reshape', 'np.reshape', (['fjac', '(n, ldfjac)'], {}), '(fjac, (n, ldfjac))\n', (2020, 2039), True, 'import numpy as np\n'), ((2823, 2852), 'numpy.reshape', 'np.reshape', (['fjac', '(n, ldfjac)'], {}), '(fjac, (n, ldfjac))\n', (2833, 2852), True, 'import numpy as np\n'), ((6207, 6221), 'numpy.finfo', 'np.finfo', (['real'], {}), '(real)\n', (6215, 6221), True, 'import numpy as np\n'), ((8593, 8607), 'numpy.finfo', 'np.finfo', (['real'], {}), '(real)\n', (8601, 8607), True, 'import numpy as np\n'), ((11177, 11191), 'numpy.finfo', 'np.finfo', (['real'], {}), '(real)\n', (11185, 11191), True, 'import numpy as np\n'), ((12565, 12579), 'numpy.finfo', 'np.finfo', (['real'], {}), '(real)\n', (12573, 12579), True, 'import numpy as np\n'), ((14897, 14911), 'numpy.finfo', 'np.finfo', (['real'], {}), '(real)\n', (14905, 14911), True, 'import numpy as np\n'), ((16440, 16454), 'numpy.finfo', 'np.finfo', (['real'], {}), '(real)\n', (16448, 16454), True, 'import numpy as np\n'), ((16489, 16503), 'numpy.finfo', 'np.finfo', (['real'], {}), '(real)\n', (16497, 16503), True, 'import numpy as np\n'), ((18838, 18852), 'numpy.finfo', 'np.finfo', (['real'], {}), '(real)\n', (18846, 18852), True, 'import numpy as np\n'), ((21363, 21377), 'numpy.finfo', 'np.finfo', (['real'], {}), '(real)\n', (21371, 21377), True, 'import numpy as np\n'), ((21412, 21426), 'numpy.finfo', 'np.finfo', (['real'], {}), '(real)\n', (21420, 21426), True, 'import numpy as np\n'), ((23953, 23967), 'numpy.finfo', 'np.finfo', (['real'], {}), '(real)\n', (23961, 23967), True, 'import numpy as np\n'), ((25547, 25561), 'numpy.finfo', 'np.finfo', (['real'], {}), '(real)\n', (25555, 25561), True, 'import numpy as np\n'), ((25596, 25610), 'numpy.finfo', 'np.finfo', (['real'], {}), '(real)\n', (25604, 25610), True, 'import numpy as np\n')]
# -*- coding:utf-8 -*- """ Project : numpy File Name : 17_to_18_legend_annotate Author : Focus Date : 8/24/2021 12:42 AM Keywords : legend, annotate Abstract : Param : Usage : py 17_to_18_legend_annotate Reference : """ import pandas_datareader as pdr import numpy as np import matplotlib.pyplot as plt from matplotlib.dates import DateFormatter from matplotlib.dates import DayLocator from matplotlib.dates import MonthLocator import mplfinance as plf from datetime import date import sys symbol = "DISH" df = pdr.data.get_data_yahoo("DISH", start="2012-12-01", end="2013-12-01") dates = np.array(df.index) close = df["Close"] fig = plt.figure() ax = fig.add_subplot(111) emas = [] # move average shift for i in range(9, 19, 3): weights = np.exp(np.linspace(-1.0, 0.0, i)) weights = weights / weights.sum() ema = np.convolve(weights, close)[i-1: -i+1] idx = (i - 6) / 3 ax.plot(dates[i-1:], ema, lw=idx, label="EMA(%s)" % (i)) data = np.column_stack((dates[i-1:].astype(np.float32), ema)) emas.append(np.rec.fromrecords( data, names=["dates", "ema"])) print("Second 2") first = emas[0]["ema"].flatten() second = emas[1]["ema"].flatten() bools = np.abs(first[-len(second):] - second) / second < 0.0001 xpoints = np.compress(bools, emas[1]) for xpoint in xpoints: ax.annotate("x", xy=xpoint, textcoords="offset points", xytext=(-50, 30), arrowprops=dict(arrowstyle="->")) print("Section 3") leg = ax.legend(loc="best", fancybox=True) leg.get_frame().set_alpha(0.5) alldays = DayLocator() months = MonthLocator() month_formatter = DateFormatter("%b %Y") ax.plot(dates, close, lw=1.0, label="Close") ax.xaxis.set_major_locator(months) ax.xaxis.set_minor_locator(alldays) ax.xaxis.set_major_formatter(month_formatter) ax.grid(True) fig.autofmt_xdate() plt.show()
[ "pandas_datareader.data.get_data_yahoo", "matplotlib.dates.MonthLocator", "matplotlib.pyplot.show", "matplotlib.dates.DayLocator", "numpy.convolve", "numpy.rec.fromrecords", "matplotlib.pyplot.figure", "matplotlib.dates.DateFormatter", "numpy.array", "numpy.linspace", "numpy.compress" ]
[((535, 604), 'pandas_datareader.data.get_data_yahoo', 'pdr.data.get_data_yahoo', (['"""DISH"""'], {'start': '"""2012-12-01"""', 'end': '"""2013-12-01"""'}), "('DISH', start='2012-12-01', end='2013-12-01')\n", (558, 604), True, 'import pandas_datareader as pdr\n'), ((613, 631), 'numpy.array', 'np.array', (['df.index'], {}), '(df.index)\n', (621, 631), True, 'import numpy as np\n'), ((658, 670), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (668, 670), True, 'import matplotlib.pyplot as plt\n'), ((1264, 1291), 'numpy.compress', 'np.compress', (['bools', 'emas[1]'], {}), '(bools, emas[1])\n', (1275, 1291), True, 'import numpy as np\n'), ((1547, 1559), 'matplotlib.dates.DayLocator', 'DayLocator', ([], {}), '()\n', (1557, 1559), False, 'from matplotlib.dates import DayLocator\n'), ((1569, 1583), 'matplotlib.dates.MonthLocator', 'MonthLocator', ([], {}), '()\n', (1581, 1583), False, 'from matplotlib.dates import MonthLocator\n'), ((1602, 1624), 'matplotlib.dates.DateFormatter', 'DateFormatter', (['"""%b %Y"""'], {}), "('%b %Y')\n", (1615, 1624), False, 'from matplotlib.dates import DateFormatter\n'), ((1821, 1831), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (1829, 1831), True, 'import matplotlib.pyplot as plt\n'), ((775, 800), 'numpy.linspace', 'np.linspace', (['(-1.0)', '(0.0)', 'i'], {}), '(-1.0, 0.0, i)\n', (786, 800), True, 'import numpy as np\n'), ((850, 877), 'numpy.convolve', 'np.convolve', (['weights', 'close'], {}), '(weights, close)\n', (861, 877), True, 'import numpy as np\n'), ((1054, 1102), 'numpy.rec.fromrecords', 'np.rec.fromrecords', (['data'], {'names': "['dates', 'ema']"}), "(data, names=['dates', 'ema'])\n", (1072, 1102), True, 'import numpy as np\n')]
#!/usr/bin/env python3 import numpy as np RNNCell = __import__('0-rnn_cell').RNNCell rnn = __import__('1-rnn').rnn np.random.seed(1) rnn_cell = RNNCell(10, 15, 5) rnn_cell.bh = np.random.randn(1, 15) rnn_cell.by = np.random.randn(1, 5) X = np.random.randn(6, 8, 10) h_0 = np.zeros((8, 15)) H, Y = rnn(rnn_cell, X, h_0) print(H.shape) print(H) print(Y.shape) print(Y)
[ "numpy.zeros", "numpy.random.seed", "numpy.random.randn" ]
[((117, 134), 'numpy.random.seed', 'np.random.seed', (['(1)'], {}), '(1)\n', (131, 134), True, 'import numpy as np\n'), ((179, 201), 'numpy.random.randn', 'np.random.randn', (['(1)', '(15)'], {}), '(1, 15)\n', (194, 201), True, 'import numpy as np\n'), ((216, 237), 'numpy.random.randn', 'np.random.randn', (['(1)', '(5)'], {}), '(1, 5)\n', (231, 237), True, 'import numpy as np\n'), ((242, 267), 'numpy.random.randn', 'np.random.randn', (['(6)', '(8)', '(10)'], {}), '(6, 8, 10)\n', (257, 267), True, 'import numpy as np\n'), ((274, 291), 'numpy.zeros', 'np.zeros', (['(8, 15)'], {}), '((8, 15))\n', (282, 291), True, 'import numpy as np\n')]
from LibrasVideoSegmentation import LibrasVideoSegmentation from os.path import split from tqdm import tqdm import pandas as pd from pathlib import Path from cupy import fft import cupy as cp # from cusignal import firwin from scipy.signal import lfilter, firwin import numpy as np from json import dump from multiprocessing import Queue, Process, cpu_count from VariationCalcMethods import runner BASE_PATH = r'E:\Backups\Cefet\OneDrive - cefet-rj.br\Dataset Lourenco\Vídeos\Base multilingue' ENERGY_LIMIT = 0.75 RESULT_FOLDER = './results_cefet' NUM_TAPS = 20 def read_labels(file='labels base cefet.csv'): return pd.read_csv(file) if __name__ == '__main__': out_queue = Queue() in_queue = Queue() processes = [Process(target=runner, args=(in_queue, out_queue), daemon=True) for _ in range(cpu_count())] for p in processes: p.start() df = read_labels() videos = df['video'].unique() base_path = Path(BASE_PATH) result_folder = Path(RESULT_FOLDER) result_folder.mkdir(parents=True, exist_ok=True) tq = tqdm(list(base_path.glob('*/*.mp4')), 'Videos: ') for video in tq: # type: Path rel_video = video.relative_to(base_path) # type: Path tq.write(f'Reading {rel_video}') video_folder = result_folder / rel_video.parent / rel_video.stem video_folder.mkdir(exist_ok=True, parents=True) file = video proc = LibrasVideoSegmentation(file.__str__()) variation = proc.calc_variations(in_queue, out_queue, 'EQUALIZED_SUM') np.save(video_folder / 'variation', variation) variation = cp.asarray(variation) hz = 1 / proc.fps yfft_eq_sum = fft.fft(variation) xfft_eq_sum = fft.fftfreq(variation.size, hz)[:variation.size // 2] sum_energy_eq_sum = cp.cumsum(2.0 / variation.size * cp.abs(yfft_eq_sum[0:variation.size // 2])) eq_sum_limiar_pc_energy = sum_energy_eq_sum.max() * ENERGY_LIMIT frequency = float(xfft_eq_sum[sum_energy_eq_sum <= eq_sum_limiar_pc_energy].max()) filter_coef = firwin(NUM_TAPS, frequency, fs=2/hz) result = lfilter(filter_coef, 1, cp.asnumpy(variation)) np.save(video_folder / 'filtered', result) result = cp.asarray(result) subs = cp.diff(result) subs2 = cp.diff(subs) critical_points = (cp.sign(subs[1:]) != cp.sign(subs[:-1])).astype(bool) maxes = critical_points & (subs2 < 0).astype(bool) mins = critical_points & (subs2 > 0).astype(bool) cp.save(video_folder / 'maxes', maxes) cp.save(video_folder / 'mins', mins) cp.save(video_folder / 'diff', subs) cp.save(video_folder / 'diff2', subs2) with (video_folder / 'metadata.json').open('w') as fp: dump({ 'hz': hz, 'frequency': frequency, }, fp)
[ "json.dump", "numpy.save", "cupy.asarray", "pandas.read_csv", "cupy.abs", "scipy.signal.firwin", "cupy.sign", "pathlib.Path", "cupy.fft.fftfreq", "cupy.asnumpy", "multiprocessing.Queue", "cupy.fft.fft", "cupy.save", "multiprocessing.Process", "cupy.diff", "multiprocessing.cpu_count" ]
[((624, 641), 'pandas.read_csv', 'pd.read_csv', (['file'], {}), '(file)\n', (635, 641), True, 'import pandas as pd\n'), ((687, 694), 'multiprocessing.Queue', 'Queue', ([], {}), '()\n', (692, 694), False, 'from multiprocessing import Queue, Process, cpu_count\n'), ((710, 717), 'multiprocessing.Queue', 'Queue', ([], {}), '()\n', (715, 717), False, 'from multiprocessing import Queue, Process, cpu_count\n'), ((960, 975), 'pathlib.Path', 'Path', (['BASE_PATH'], {}), '(BASE_PATH)\n', (964, 975), False, 'from pathlib import Path\n'), ((996, 1015), 'pathlib.Path', 'Path', (['RESULT_FOLDER'], {}), '(RESULT_FOLDER)\n', (1000, 1015), False, 'from pathlib import Path\n'), ((735, 798), 'multiprocessing.Process', 'Process', ([], {'target': 'runner', 'args': '(in_queue, out_queue)', 'daemon': '(True)'}), '(target=runner, args=(in_queue, out_queue), daemon=True)\n', (742, 798), False, 'from multiprocessing import Queue, Process, cpu_count\n'), ((1559, 1605), 'numpy.save', 'np.save', (["(video_folder / 'variation')", 'variation'], {}), "(video_folder / 'variation', variation)\n", (1566, 1605), True, 'import numpy as np\n'), ((1626, 1647), 'cupy.asarray', 'cp.asarray', (['variation'], {}), '(variation)\n', (1636, 1647), True, 'import cupy as cp\n'), ((1696, 1714), 'cupy.fft.fft', 'fft.fft', (['variation'], {}), '(variation)\n', (1703, 1714), False, 'from cupy import fft\n'), ((2082, 2120), 'scipy.signal.firwin', 'firwin', (['NUM_TAPS', 'frequency'], {'fs': '(2 / hz)'}), '(NUM_TAPS, frequency, fs=2 / hz)\n', (2088, 2120), False, 'from scipy.signal import lfilter, firwin\n'), ((2191, 2233), 'numpy.save', 'np.save', (["(video_folder / 'filtered')", 'result'], {}), "(video_folder / 'filtered', result)\n", (2198, 2233), True, 'import numpy as np\n'), ((2251, 2269), 'cupy.asarray', 'cp.asarray', (['result'], {}), '(result)\n', (2261, 2269), True, 'import cupy as cp\n'), ((2285, 2300), 'cupy.diff', 'cp.diff', (['result'], {}), '(result)\n', (2292, 2300), True, 'import cupy as cp\n'), ((2317, 2330), 'cupy.diff', 'cp.diff', (['subs'], {}), '(subs)\n', (2324, 2330), True, 'import cupy as cp\n'), ((2537, 2575), 'cupy.save', 'cp.save', (["(video_folder / 'maxes')", 'maxes'], {}), "(video_folder / 'maxes', maxes)\n", (2544, 2575), True, 'import cupy as cp\n'), ((2584, 2620), 'cupy.save', 'cp.save', (["(video_folder / 'mins')", 'mins'], {}), "(video_folder / 'mins', mins)\n", (2591, 2620), True, 'import cupy as cp\n'), ((2629, 2665), 'cupy.save', 'cp.save', (["(video_folder / 'diff')", 'subs'], {}), "(video_folder / 'diff', subs)\n", (2636, 2665), True, 'import cupy as cp\n'), ((2674, 2712), 'cupy.save', 'cp.save', (["(video_folder / 'diff2')", 'subs2'], {}), "(video_folder / 'diff2', subs2)\n", (2681, 2712), True, 'import cupy as cp\n'), ((1737, 1768), 'cupy.fft.fftfreq', 'fft.fftfreq', (['variation.size', 'hz'], {}), '(variation.size, hz)\n', (1748, 1768), False, 'from cupy import fft\n'), ((2160, 2181), 'cupy.asnumpy', 'cp.asnumpy', (['variation'], {}), '(variation)\n', (2170, 2181), True, 'import cupy as cp\n'), ((2788, 2832), 'json.dump', 'dump', (["{'hz': hz, 'frequency': frequency}", 'fp'], {}), "({'hz': hz, 'frequency': frequency}, fp)\n", (2792, 2832), False, 'from json import dump\n'), ((831, 842), 'multiprocessing.cpu_count', 'cpu_count', ([], {}), '()\n', (840, 842), False, 'from multiprocessing import Queue, Process, cpu_count\n'), ((1852, 1894), 'cupy.abs', 'cp.abs', (['yfft_eq_sum[0:variation.size // 2]'], {}), '(yfft_eq_sum[0:variation.size // 2])\n', (1858, 1894), True, 'import cupy as cp\n'), ((2358, 2375), 'cupy.sign', 'cp.sign', (['subs[1:]'], {}), '(subs[1:])\n', (2365, 2375), True, 'import cupy as cp\n'), ((2379, 2397), 'cupy.sign', 'cp.sign', (['subs[:-1]'], {}), '(subs[:-1])\n', (2386, 2397), True, 'import cupy as cp\n')]
import numpy as np import pytest from helpers import get_expected_if_it_exists from nanomesh.image2mesh._mesher3d import BoundingBox, volume2mesh def compare_mesh_results(mesh_container, expected_fn): """`result_mesh` is an instance of TetraMesh, and `expected_fn` the filename of the mesh to compare to.""" expected_mesh_container = get_expected_if_it_exists(expected_fn, result=mesh_container) cell_type = 'tetra' mesh = mesh_container.get(cell_type) expected_mesh = expected_mesh_container.get(cell_type) assert mesh.points.shape == expected_mesh.points.shape assert mesh.cells.shape == expected_mesh.cells.shape np.testing.assert_allclose(mesh.points, expected_mesh.points) np.testing.assert_allclose(mesh.cells, expected_mesh.cells) np.testing.assert_allclose(mesh.region_markers, expected_mesh.region_markers) for key in expected_mesh.cell_data: try: np.testing.assert_allclose(mesh.cell_data[key], expected_mesh.cell_data[key]) except KeyError: if key not in ('physical', 'geometrical'): raise @pytest.mark.xfail( pytest.OS_DOES_NOT_MATCH_DATA_GEN, raises=AssertionError, reason=('No way of currently ensuring meshes on OSX / Linux / Windows ' 'are exactly the same.')) def test_volume2mesh(segmented_image_3d): """Test 3D mesh generation.""" expected_fn = 'segmented_mesh_3d.msh' mesh_container = volume2mesh(segmented_image_3d) assert 'tetgen:ref' in mesh_container.cell_data compare_mesh_results(mesh_container, expected_fn) def test_BoundingBox_center(): """Test BoundingBox init / center.""" bbox = BoundingBox( xmin=0.0, xmax=10.0, ymin=20.0, ymax=30.0, zmin=40.0, zmax=50.0, ) np.testing.assert_equal(bbox.center, (5, 25, 45)) def test_BoundingBox_from_shape(): """Test BoundingBox .from_shape / .dimensions.""" shape = np.array((10, 20, 30)) bbox = BoundingBox.from_shape(shape) np.testing.assert_equal(bbox.dimensions, shape - 1) def test_BoundingBox_from_points(): """Test BoundingBox .from_points / to_points.""" points = np.array([ (10, 20, 30), (5, 5, 0), (0, 0, 5), ]) bbox = BoundingBox.from_points(points) corners = bbox.to_points() expected = ([0, 0, 0], [0, 0, 30], [0, 20, 0], [0, 20, 30], [10, 0, 0], [10, 0, 30], [10, 20, 0], [10, 20, 30]) np.testing.assert_equal(corners, expected)
[ "helpers.get_expected_if_it_exists", "nanomesh.image2mesh._mesher3d.BoundingBox", "nanomesh.image2mesh._mesher3d.volume2mesh", "nanomesh.image2mesh._mesher3d.BoundingBox.from_points", "numpy.array", "numpy.testing.assert_equal", "numpy.testing.assert_allclose", "nanomesh.image2mesh._mesher3d.BoundingB...
[((1242, 1424), 'pytest.mark.xfail', 'pytest.mark.xfail', (['pytest.OS_DOES_NOT_MATCH_DATA_GEN'], {'raises': 'AssertionError', 'reason': '"""No way of currently ensuring meshes on OSX / Linux / Windows are exactly the same."""'}), "(pytest.OS_DOES_NOT_MATCH_DATA_GEN, raises=AssertionError,\n reason=\n 'No way of currently ensuring meshes on OSX / Linux / Windows are exactly the same.'\n )\n", (1259, 1424), False, 'import pytest\n'), ((349, 410), 'helpers.get_expected_if_it_exists', 'get_expected_if_it_exists', (['expected_fn'], {'result': 'mesh_container'}), '(expected_fn, result=mesh_container)\n', (374, 410), False, 'from helpers import get_expected_if_it_exists\n'), ((714, 775), 'numpy.testing.assert_allclose', 'np.testing.assert_allclose', (['mesh.points', 'expected_mesh.points'], {}), '(mesh.points, expected_mesh.points)\n', (740, 775), True, 'import numpy as np\n'), ((780, 839), 'numpy.testing.assert_allclose', 'np.testing.assert_allclose', (['mesh.cells', 'expected_mesh.cells'], {}), '(mesh.cells, expected_mesh.cells)\n', (806, 839), True, 'import numpy as np\n'), ((845, 922), 'numpy.testing.assert_allclose', 'np.testing.assert_allclose', (['mesh.region_markers', 'expected_mesh.region_markers'], {}), '(mesh.region_markers, expected_mesh.region_markers)\n', (871, 922), True, 'import numpy as np\n'), ((1582, 1613), 'nanomesh.image2mesh._mesher3d.volume2mesh', 'volume2mesh', (['segmented_image_3d'], {}), '(segmented_image_3d)\n', (1593, 1613), False, 'from nanomesh.image2mesh._mesher3d import BoundingBox, volume2mesh\n'), ((1808, 1884), 'nanomesh.image2mesh._mesher3d.BoundingBox', 'BoundingBox', ([], {'xmin': '(0.0)', 'xmax': '(10.0)', 'ymin': '(20.0)', 'ymax': '(30.0)', 'zmin': '(40.0)', 'zmax': '(50.0)'}), '(xmin=0.0, xmax=10.0, ymin=20.0, ymax=30.0, zmin=40.0, zmax=50.0)\n', (1819, 1884), False, 'from nanomesh.image2mesh._mesher3d import BoundingBox, volume2mesh\n'), ((1944, 1993), 'numpy.testing.assert_equal', 'np.testing.assert_equal', (['bbox.center', '(5, 25, 45)'], {}), '(bbox.center, (5, 25, 45))\n', (1967, 1993), True, 'import numpy as np\n'), ((2097, 2119), 'numpy.array', 'np.array', (['(10, 20, 30)'], {}), '((10, 20, 30))\n', (2105, 2119), True, 'import numpy as np\n'), ((2131, 2160), 'nanomesh.image2mesh._mesher3d.BoundingBox.from_shape', 'BoundingBox.from_shape', (['shape'], {}), '(shape)\n', (2153, 2160), False, 'from nanomesh.image2mesh._mesher3d import BoundingBox, volume2mesh\n'), ((2165, 2216), 'numpy.testing.assert_equal', 'np.testing.assert_equal', (['bbox.dimensions', '(shape - 1)'], {}), '(bbox.dimensions, shape - 1)\n', (2188, 2216), True, 'import numpy as np\n'), ((2321, 2367), 'numpy.array', 'np.array', (['[(10, 20, 30), (5, 5, 0), (0, 0, 5)]'], {}), '([(10, 20, 30), (5, 5, 0), (0, 0, 5)])\n', (2329, 2367), True, 'import numpy as np\n'), ((2410, 2441), 'nanomesh.image2mesh._mesher3d.BoundingBox.from_points', 'BoundingBox.from_points', (['points'], {}), '(points)\n', (2433, 2441), False, 'from nanomesh.image2mesh._mesher3d import BoundingBox, volume2mesh\n'), ((2610, 2652), 'numpy.testing.assert_equal', 'np.testing.assert_equal', (['corners', 'expected'], {}), '(corners, expected)\n', (2633, 2652), True, 'import numpy as np\n'), ((1020, 1097), 'numpy.testing.assert_allclose', 'np.testing.assert_allclose', (['mesh.cell_data[key]', 'expected_mesh.cell_data[key]'], {}), '(mesh.cell_data[key], expected_mesh.cell_data[key])\n', (1046, 1097), True, 'import numpy as np\n')]
from pathlib import Path from PIL import Image from pycocotools.coco import COCO import os from torchvision import transforms import numpy as np from store.memory_hierarchy import StorageAttributes, StorageComponents from store.store import DataStore, Metadata, MetadataField class CocoDetection(DataStore): def __init__(self, annFile, **kwargs): super(CocoDetection, self).__init__(**kwargs) self.dataset_name = "ms-coco-train-2017" self.metadata = Metadata(self).load() self.created = False train_metadata = self.metadata.get(self.TRAIN_FOLDER) if train_metadata: self.key_size = train_metadata.get(MetadataField.KEY_SIZE) self.value_size = train_metadata.get(MetadataField.VALUE_SIZE) self.created = True else: self.key_size = self.value_size = None self.coco = COCO(annFile) self.ids = list(self.coco.imgs.keys()) self.ids.sort() # Tentative number of files, might change self.num_train_files = 10 self.num_points_in_numpy_batch = 500 def count_num_points(self): self.num_train_points = len(self.ids) def generate_IR(self): if self.created: print("IR already created in folder ", self.get_data_folder_path()) return data_folder_path = self.get_data_folder_path() if not Path(data_folder_path).exists(): print("Creating directory(s)", data_folder_path) Path(data_folder_path).mkdir(parents=True, exist_ok=True) # Create train and test directories train_folder_path = data_folder_path + '/' + self.TRAIN_FOLDER test_folder_path = data_folder_path + '/' + self.TEST_FOLDER for path in [train_folder_path, test_folder_path]: if not Path(path).exists(): print("Creating directory", path) Path(path).mkdir(parents=True, exist_ok=True) num_points_in_numpy_batch = self.num_points_in_numpy_batch numpy_batches = [] cur_numpy_batch = [] i = 0 while i < self.num_train_points: cur_numpy_batch.append(i) i += 1 if i % num_points_in_numpy_batch == 0: numpy_batches.append(cur_numpy_batch) cur_numpy_batch = [] # Incomplete batch if len(cur_numpy_batch) != 0: numpy_batches.append(cur_numpy_batch) num_batches_in_file = int(len(numpy_batches)/self.num_train_files + 1) batches_in_files = [] cur_file_batches = [] i = 0 while i < len(numpy_batches): cur_file_batches.append(numpy_batches[i]) i += 1 if i % num_batches_in_file == 0: batches_in_files.append(cur_file_batches) cur_file_batches = [] if i % num_batches_in_file != 0: batches_in_files.append(cur_file_batches) # Distributed the batches roughly over files, might require # lesser number of files if len(batches_in_files) != self.num_train_files: self.num_train_files = len(batches_in_files) # Write metadata before creating files self.write_metadata(batches_in_files) for i in range(len(batches_in_files)): fname = train_folder_path + '/' + self.DATA_FILE.format(i) f = Path(fname).open('ab') for batch in batches_in_files[i]: # create a batch nparr = [[self.get_image(i), self.ids[i]] for i in batch] nparr = np.array(nparr) np.save(f, nparr) f.close() print("Finished creating file ", fname) def get_image(self, index): """ :param index: Index of the image to get :return: a PIL RGB image object of shape 224*224*3 """ img_id = self.ids[index] path = self.coco.loadImgs(img_id)[0]['file_name'] img = Image.open(os.path.join(self.input_data_folder, path)).convert('RGB') # NOTE:Crop the image. Hardcoded for now. img = transforms.RandomResizedCrop(224)(img) img = np.array(img) img = img.reshape(3, 224, 224) return img def write_metadata(self, batches_in_files): metadata_dict = {} train_metadata = { MetadataField.KEY_SIZE: 4, # bytes MetadataField.VALUE_SIZE: 0, # Does not matter } train_files = {} for i in range(self.num_train_files): batches = batches_in_files[i] chunk_count = len(batches) kv_count = 0 for batch in batches: kv_count += len(batch) train_files[self.DATA_FILE.format(i)] = { MetadataField.KV_COUNT: kv_count, MetadataField.CHUNK_COUNT: chunk_count } train_metadata[MetadataField.FILES] = train_files metadata_dict[self.TRAIN_FOLDER] = train_metadata metadata = Metadata(self) metadata.store(metadata_dict) self.metadata = metadata.load() # Skipping test metadata, not generating IR for test files def get_data_folder_path(self): return self.mem_config.get(StorageComponents.HDD)\ .get(StorageAttributes.ONE_ACCESS_DIR) + '/' + self.dataset_name
[ "numpy.save", "pycocotools.coco.COCO", "pathlib.Path", "numpy.array", "store.store.Metadata", "torchvision.transforms.RandomResizedCrop", "os.path.join" ]
[((885, 898), 'pycocotools.coco.COCO', 'COCO', (['annFile'], {}), '(annFile)\n', (889, 898), False, 'from pycocotools.coco import COCO\n'), ((4183, 4196), 'numpy.array', 'np.array', (['img'], {}), '(img)\n', (4191, 4196), True, 'import numpy as np\n'), ((5033, 5047), 'store.store.Metadata', 'Metadata', (['self'], {}), '(self)\n', (5041, 5047), False, 'from store.store import DataStore, Metadata, MetadataField\n'), ((4130, 4163), 'torchvision.transforms.RandomResizedCrop', 'transforms.RandomResizedCrop', (['(224)'], {}), '(224)\n', (4158, 4163), False, 'from torchvision import transforms\n'), ((481, 495), 'store.store.Metadata', 'Metadata', (['self'], {}), '(self)\n', (489, 495), False, 'from store.store import DataStore, Metadata, MetadataField\n'), ((3603, 3618), 'numpy.array', 'np.array', (['nparr'], {}), '(nparr)\n', (3611, 3618), True, 'import numpy as np\n'), ((3635, 3652), 'numpy.save', 'np.save', (['f', 'nparr'], {}), '(f, nparr)\n', (3642, 3652), True, 'import numpy as np\n'), ((1401, 1423), 'pathlib.Path', 'Path', (['data_folder_path'], {}), '(data_folder_path)\n', (1405, 1423), False, 'from pathlib import Path\n'), ((1507, 1529), 'pathlib.Path', 'Path', (['data_folder_path'], {}), '(data_folder_path)\n', (1511, 1529), False, 'from pathlib import Path\n'), ((3403, 3414), 'pathlib.Path', 'Path', (['fname'], {}), '(fname)\n', (3407, 3414), False, 'from pathlib import Path\n'), ((4007, 4049), 'os.path.join', 'os.path.join', (['self.input_data_folder', 'path'], {}), '(self.input_data_folder, path)\n', (4019, 4049), False, 'import os\n'), ((1828, 1838), 'pathlib.Path', 'Path', (['path'], {}), '(path)\n', (1832, 1838), False, 'from pathlib import Path\n'), ((1915, 1925), 'pathlib.Path', 'Path', (['path'], {}), '(path)\n', (1919, 1925), False, 'from pathlib import Path\n')]
# -*- coding: utf-8 -*- """Test utils for processing numeric literals""" import unittest import numpy as np from poem.instance_creation_factories.triples_numeric_literals_factory import TriplesNumericLiteralsFactory from poem.preprocessing.triples_preprocessing_utils.basic_triple_utils import create_entity_and_relation_mappings class NumericLiteralsUtilsTests(unittest.TestCase): """Class for testing utils for processing numeric literals.tsv.""" triples = np.array([['peter', 'likes', 'chocolate_cake'], ['chocolate_cake', 'isA', 'dish'], ['susan', 'likes', 'pizza']], dtype=np.str) literals = np.array([['peter', '/lit/hasAge', '30'], ['peter', '/lit/hasHeight', '185'], ['peter', '/lit/hasChildren', '2'], ['susan', '/lit/hasAge', '28'], ['susan', '/lit/hasHeight', '170'], ], dtype=np.str) # literals_file = '/Users/mali/PycharmProjects/POEM_develop/tests/resources/numerical_literals.txt' def test_create_cwa_instances(self): entity_to_id, relation_to_id = create_entity_and_relation_mappings(triples=self.triples) factory = TriplesNumericLiteralsFactory(entity_to_id=entity_to_id, relation_to_id=relation_to_id, numeric_triples=self.literals) instances = factory.create_cwa_instances(triples=self.triples) literals = instances.multimodal_data['numeric_literlas'] literals_to_id = instances.data_relation_to_id id_peter = entity_to_id['peter'] id_age = literals_to_id['/lit/hasAge'] id_height = literals_to_id['/lit/hasHeight'] id_num_children = literals_to_id['/lit/hasChildren'] self.assertEqual(literals[id_peter, id_age], 30) self.assertEqual(literals[id_peter, id_height], 185) self.assertEqual(literals[id_peter, id_num_children], 2) id_susan = entity_to_id['susan'] id_age = literals_to_id['/lit/hasAge'] id_height = literals_to_id['/lit/hasHeight'] id_num_children = literals_to_id['/lit/hasChildren'] self.assertEqual(literals[id_susan, id_age], 28) self.assertEqual(literals[id_susan, id_height], 170) self.assertEqual(literals[id_susan, id_num_children], 0) id_chocolate_cake = entity_to_id['chocolate_cake'] id_age = literals_to_id['/lit/hasAge'] id_height = literals_to_id['/lit/hasHeight'] id_num_children = literals_to_id['/lit/hasChildren'] self.assertEqual(literals[id_chocolate_cake, id_age], 0) self.assertEqual(literals[id_chocolate_cake, id_height], 0) self.assertEqual(literals[id_chocolate_cake, id_num_children], 0) # Test creation of labels print(instances.labels)
[ "poem.instance_creation_factories.triples_numeric_literals_factory.TriplesNumericLiteralsFactory", "numpy.array", "poem.preprocessing.triples_preprocessing_utils.basic_triple_utils.create_entity_and_relation_mappings" ]
[((472, 602), 'numpy.array', 'np.array', (["[['peter', 'likes', 'chocolate_cake'], ['chocolate_cake', 'isA', 'dish'], [\n 'susan', 'likes', 'pizza']]"], {'dtype': 'np.str'}), "([['peter', 'likes', 'chocolate_cake'], ['chocolate_cake', 'isA',\n 'dish'], ['susan', 'likes', 'pizza']], dtype=np.str)\n", (480, 602), True, 'import numpy as np\n'), ((663, 868), 'numpy.array', 'np.array', (["[['peter', '/lit/hasAge', '30'], ['peter', '/lit/hasHeight', '185'], [\n 'peter', '/lit/hasChildren', '2'], ['susan', '/lit/hasAge', '28'], [\n 'susan', '/lit/hasHeight', '170']]"], {'dtype': 'np.str'}), "([['peter', '/lit/hasAge', '30'], ['peter', '/lit/hasHeight', '185'\n ], ['peter', '/lit/hasChildren', '2'], ['susan', '/lit/hasAge', '28'],\n ['susan', '/lit/hasHeight', '170']], dtype=np.str)\n", (671, 868), True, 'import numpy as np\n'), ((1173, 1230), 'poem.preprocessing.triples_preprocessing_utils.basic_triple_utils.create_entity_and_relation_mappings', 'create_entity_and_relation_mappings', ([], {'triples': 'self.triples'}), '(triples=self.triples)\n', (1208, 1230), False, 'from poem.preprocessing.triples_preprocessing_utils.basic_triple_utils import create_entity_and_relation_mappings\n'), ((1250, 1373), 'poem.instance_creation_factories.triples_numeric_literals_factory.TriplesNumericLiteralsFactory', 'TriplesNumericLiteralsFactory', ([], {'entity_to_id': 'entity_to_id', 'relation_to_id': 'relation_to_id', 'numeric_triples': 'self.literals'}), '(entity_to_id=entity_to_id, relation_to_id=\n relation_to_id, numeric_triples=self.literals)\n', (1279, 1373), False, 'from poem.instance_creation_factories.triples_numeric_literals_factory import TriplesNumericLiteralsFactory\n')]
"""Probe a voxel dataset at specified points and plot a histogram of the values""" from vedo import * from vedo.pyplot import histogram import numpy as np vol = Volume(dataurl+'embryo.slc') pts = np.random.rand(5000, 3)*256 mpts = probePoints(vol, pts).pointSize(3) mpts.print() # valid = mpts.pointdata['vtkValidPointMask'] scals = mpts.pointdata['SLCImage'] his = histogram(scals, xtitle='probed voxel value', xlim=(5,100)) show([(vol, Axes(vol), mpts, __doc__), his], N=2, sharecam=False).close()
[ "vedo.pyplot.histogram", "numpy.random.rand" ]
[((371, 431), 'vedo.pyplot.histogram', 'histogram', (['scals'], {'xtitle': '"""probed voxel value"""', 'xlim': '(5, 100)'}), "(scals, xtitle='probed voxel value', xlim=(5, 100))\n", (380, 431), False, 'from vedo.pyplot import histogram\n'), ((198, 221), 'numpy.random.rand', 'np.random.rand', (['(5000)', '(3)'], {}), '(5000, 3)\n', (212, 221), True, 'import numpy as np\n')]
import onnxruntime import numpy as np from pprint import pprint ### Batch N test BATCH=5 # ONNX onnx_session = onnxruntime.InferenceSession( 'model_float32_camera_Nx224x224.onnx', providers=[ 'CUDAExecutionProvider', ], ) # Inference input_name = onnx_session.get_inputs()[0].name results = onnx_session.run( None, {input_name: np.ones([BATCH,3,224,224], dtype=np.float32)} ) for result in results: pprint(result)
[ "onnxruntime.InferenceSession", "numpy.ones", "pprint.pprint" ]
[((112, 220), 'onnxruntime.InferenceSession', 'onnxruntime.InferenceSession', (['"""model_float32_camera_Nx224x224.onnx"""'], {'providers': "['CUDAExecutionProvider']"}), "('model_float32_camera_Nx224x224.onnx',\n providers=['CUDAExecutionProvider'])\n", (140, 220), False, 'import onnxruntime\n'), ((432, 446), 'pprint.pprint', 'pprint', (['result'], {}), '(result)\n', (438, 446), False, 'from pprint import pprint\n'), ((357, 404), 'numpy.ones', 'np.ones', (['[BATCH, 3, 224, 224]'], {'dtype': 'np.float32'}), '([BATCH, 3, 224, 224], dtype=np.float32)\n', (364, 404), True, 'import numpy as np\n')]
import numpy as np import os import pickle from load_data import load_channels, load_angs, bin_data, bin_angs, load_states, bin_states binsize = 0.5 # resolution in seconds # from metadata; which channels recorded from ADn channeladn = {'28_140313': (8, 11)} # from metadata; which channels recorded from postsubiculum channelpos = {'28_140313': (1, 7)} channeldict = channeladn # we're analyzing ADn key = '28_140313' mouse, session = key.split('_') channels = range(channeldict[mouse + '_' + session][0], channeldict[mouse + '_' + session][1] + 1) print('\nextracting, binning and analyzing data for mouse', mouse, 'session', session, 'electrodes:', list(channels)) print('loading spike data') data = load_channels(mouse=mouse, session=session, channels=channels) print('loading behavioral data') times, angs = load_angs(mouse=mouse, session=session) wake, rem, _ = load_states(mouse=mouse, session=session) # ignore sws for now print('removing spikes with mean(r) < 0.25Hz') tmax = times[-1] nmin = tmax * 0.25 data = [dat for dat in data if len(dat) > nmin] print('binning data') # bin the neural activity bindata, bins = bin_data(data, binsize=binsize) binangs, binang_sds = bin_angs(angs, times, bins) # bin HD bin_wake, bin_sleep, _ = bin_states([wake, rem, []], bins) # bin states print('collecting data') # collect firing rates and head directions for wake and sleep bin_wake[np.isnan(binangs)] = False bin_sleep[np.isnan(binangs)] = False ts_wake, ts_sleep = bins[1:][bin_wake], bins[1:][bin_sleep] zs_wake, zs_sleep = binangs[bin_wake], binangs[bin_sleep] Y_wake, Y_sleep = [ np.array([data[bins] for data in bindata]) for bins in [bin_wake, bin_sleep] ] # match the amount of data for wake and sleep tmax = np.amin([np.sum(bin_wake), np.sum(bin_sleep)]) ts_wake, ts_sleep = ts_wake[:tmax] - ts_wake[0], ts_sleep[:tmax] - ts_sleep[0] zs_wake, zs_sleep = zs_wake[:tmax], zs_sleep[:tmax] Y_wake, Y_sleep = Y_wake[:, :tmax], Y_sleep[:, :tmax] print('saving data to pickled file') output_data = { 'Y_wake': Y_wake, 'Y_sleep': Y_sleep, 'hd_wake': zs_wake, 'hd_sleep': zs_sleep, 'ts_wake': ts_wake, 'ts_sleep': ts_sleep } pickle.dump(output_data, open('binned_data.pickled', 'wb'))
[ "load_data.load_angs", "numpy.sum", "load_data.bin_angs", "load_data.bin_data", "numpy.isnan", "load_data.load_states", "load_data.load_channels", "numpy.array", "load_data.bin_states" ]
[((733, 795), 'load_data.load_channels', 'load_channels', ([], {'mouse': 'mouse', 'session': 'session', 'channels': 'channels'}), '(mouse=mouse, session=session, channels=channels)\n', (746, 795), False, 'from load_data import load_channels, load_angs, bin_data, bin_angs, load_states, bin_states\n'), ((844, 883), 'load_data.load_angs', 'load_angs', ([], {'mouse': 'mouse', 'session': 'session'}), '(mouse=mouse, session=session)\n', (853, 883), False, 'from load_data import load_channels, load_angs, bin_data, bin_angs, load_states, bin_states\n'), ((899, 940), 'load_data.load_states', 'load_states', ([], {'mouse': 'mouse', 'session': 'session'}), '(mouse=mouse, session=session)\n', (910, 940), False, 'from load_data import load_channels, load_angs, bin_data, bin_angs, load_states, bin_states\n'), ((1160, 1191), 'load_data.bin_data', 'bin_data', (['data'], {'binsize': 'binsize'}), '(data, binsize=binsize)\n', (1168, 1191), False, 'from load_data import load_channels, load_angs, bin_data, bin_angs, load_states, bin_states\n'), ((1214, 1241), 'load_data.bin_angs', 'bin_angs', (['angs', 'times', 'bins'], {}), '(angs, times, bins)\n', (1222, 1241), False, 'from load_data import load_channels, load_angs, bin_data, bin_angs, load_states, bin_states\n'), ((1277, 1310), 'load_data.bin_states', 'bin_states', (['[wake, rem, []]', 'bins'], {}), '([wake, rem, []], bins)\n', (1287, 1310), False, 'from load_data import load_channels, load_angs, bin_data, bin_angs, load_states, bin_states\n'), ((1422, 1439), 'numpy.isnan', 'np.isnan', (['binangs'], {}), '(binangs)\n', (1430, 1439), True, 'import numpy as np\n'), ((1459, 1476), 'numpy.isnan', 'np.isnan', (['binangs'], {}), '(binangs)\n', (1467, 1476), True, 'import numpy as np\n'), ((1629, 1671), 'numpy.array', 'np.array', (['[data[bins] for data in bindata]'], {}), '([data[bins] for data in bindata])\n', (1637, 1671), True, 'import numpy as np\n'), ((1789, 1805), 'numpy.sum', 'np.sum', (['bin_wake'], {}), '(bin_wake)\n', (1795, 1805), True, 'import numpy as np\n'), ((1807, 1824), 'numpy.sum', 'np.sum', (['bin_sleep'], {}), '(bin_sleep)\n', (1813, 1824), True, 'import numpy as np\n')]
# To add a new cell, type '# %%' # To add a new markdown cell, type '# %% [markdown]' # %% from IPython import get_ipython # %% [markdown] # <h2>Minerando Dados - Visualização de Dados</h2> # # **Trabalhando com Seaborn** # # * Biblioteca para Visualização de dados em Matplotlib; # * Interface de alto nível para gráficos *estatísticos*; # * Fornece uma Interface atraente e profissional para os gráficos; # * Simples e muito intuitiva de usar. # %% [markdown] # **Quando utilizar?** # # * Útil par análise e exploração de dados; # * Apresenta análises visuais. # %% [markdown] # <h3>Carregando Dataset</h3> # %% import seaborn as sns # %% tips = sns.load_dataset('tips') # %% [markdown] # <h3>Plotando dados categóricos</h3> # # * Quando trabalhamos com variáveis categóricas temos que visualizar dados de formas diferentes; # * O *Seaborn* fornece o método *catplot()* que já contém diversos tipos de gráficos embutidos; # * Isso facilita, pois, você pode usar diferentes gráficos usando um mesmo método. # %% [markdown] # **Gráficos de barras ou também conhecidos como gráficos de colunas** # %% sns.catplot(x='sex', kind='count', palette='Set2', data=tips) # %% [markdown] # **Gráficos de barras horizontais usando a coluna *day* ** # %% sns.catplot(y='day', kind='count', palette='Set1', data=tips) # %% [markdown] # **Scatter plot com dados categóricos** # %% sns.catplot(x='day', y='total_bill', palette='Set2', data=tips) # %% [markdown] # **O parâmetro *swarm* evita sobreposições de pontos** # %% sns.catplot(x='day', y='total_bill', kind='swarm', data=tips) # %% [markdown] # **O parâmetro *hue* permite adicionarmos uma terceira variável a nossa visualização** # %% sns.catplot(x='day', y='total_bill', kind='swarm', hue='sex', palette='Dark2', data=tips) # %% [markdown] # * O parâmetro **order** permite alterarmos a ordem padrão das categorias que estão sendo exibidas; # * Isso é útil quando temos mais de um gráfico na mesma figura e queremos manter as mesmas ordens. # %% sns.catplot(x='day', y='total_bill', kind='swarm', hue='sex', order=['Sat', 'Sun', 'Fri', 'Thur'], data=tips) # %% [markdown] # **Invertendo a visualização para plots horizontais** # %% sns.catplot(x='total_bill', y='day', kind='swarm', data=tips) # %% [markdown] # <h3>Gráficos com Regressão</h3> # # * Quando temos muitas variáveis quantitativas em nossos dados é interessante visualizar como estas se relacionam; # * Podemos visualizar essas informações com linhas de Regressão; # * Com modelos de regressão simples é possível checar se existe alguma correlação entre algumas variáveis. # %% [markdown] # **Exibe a linha de regressão para visualizar a correlação entre as variáveis** # %% get_ipython().run_line_magic('matplotlib', 'inline') sns.lmplot(x='total_bill', y='tip', hue='sex', palette='Pastel1', data=tips) # %% [markdown] # **Usando o parâmetro col para segregar os gráficos pelo valor da coluna categórica *time* ** # %% get_ipython().run_line_magic('matplotlib', 'inline') sns.lmplot(x='total_bill', y='tip', hue='smoker', col='time', palette='Set2', data=tips) # %% [markdown] # **Parâmetros scatter_kws e line_kws** # %% get_ipython().run_line_magic('matplotlib', 'inline') sns.lmplot(x='total_bill', y='tip', hue='smoker', col='time', palette='Set1', data=tips, scatter_kws={'s': 90, 'alpha': 0.5}, line_kws={'lw': 4}) # %% [markdown] # **Segregando gráficos pelo parâmetro *col* e pelo parâmetro *row* ** # %% get_ipython().run_line_magic('matplotlib', 'inline') sns.lmplot(x='total_bill', y='tip', hue='smoker', col='time', row='sex', palette='Set2', data=tips) # %% [markdown] # <h2>Visualizando distribuições de observações</h2> # # * Um dataset muito grande será difícil de visualizar variáveis categóricas; # * É preciso sumarizar a distribuição dos dados para facilitar a visualização; # * Podemos usar um gráfico do tipo Boxplot para visualizar a distribuição de tais variáveis; # * Esse tipo de gráfico é muito útil para visualizar ** *Outliers* **. # %% [markdown] # **Boxplot de Dias da semana por total de conta** # %% sns.catplot(x='day', y='total_bill', kind='box', data=tips) # %% [markdown] # **Gráfico de Boxplot dos dias por total de conta e se a pessoa é fumante ou não** # %% sns.catplot(x='day', y='total_bill', hue='smoker', kind='box', data=tips) # %% [markdown] # **Boxen** # # * Tipo de boxplot com foco maior dos dados do que nos *outliers*; # * Esse tipo de gráfico é interessante quando temos grandes datasets. # %% sns.catplot(x='day', y='total_bill', kind='boxen', data=tips) # %% [markdown] # **Stripplot** # # * Esse método permite plotar a distribuição dos dados; # * Podemos combinar os dois gráficos para ter mais informação. # %% sns.catplot(x='day', y='total_bill', kind='boxen', data=tips) sns.stripplot(x='day', y='total_bill', data=tips, color='blue') # %% [markdown] # ** O método *catplot()* permite usarmos facetgrid assim podemos combinar gráficos em uma única figura** # %% get_ipython().run_line_magic('matplotlib', 'inline') sns.catplot(x='sex', y='total_bill', hue='smoker', col='time', data=tips, kind='boxen', height=4) # %% [markdown] # <h2>Violin Plot</h2> # # * Gráfico ideal para visualizar a distribuição de variáveis; # * Combinação do Boxplot com o KDE; # * Funciona bem para distribuições com picos; # * Permite uma visualização mais rica do que com o Boxplot normal. # %% [markdown] # **Violin Plot** # %% sns.catplot(x='day', y='total_bill', kind='violin', data=tips) # %% [markdown] # **Violin Horizontal** # %% sns.catplot(x='total_bill', y='day', kind='violin', data=tips) # %% [markdown] # **Usando o parâmetro Hue para ter uma terceira variável** # %% sns.catplot(x='day', y='total_bill', hue='time', kind='violin', data=tips) # %% [markdown] # **Split** # # * É possível dividir o violin plot com o parâmetro split; # * Sendo útil quando temos muitos dados para exibir. # %% sns.catplot(x='day', y='total_bill', hue='sex', split=True, kind='violin', data=tips) # %% [markdown] # **Inner** # # * Usando o parâmetro *inner* para preencher o violin plot com observações; # * Útil para destacar bem as partes que possuem mais dados. # %% sns.catplot(x='day', y='total_bill', hue='sex', split=True, inner='stick', palette='pastel', kind='violin', data=tips) # %% [markdown] # **Swarm** # # * Podemos combinar também um gráfico de swarm com o Violin Plot; # * Dessa forma fica mais explícito ainda a frequência de pontos nas partes do 'violino'. # %% sns.catplot(x='day', y='total_bill', hue='sex', split=True, palette='pastel', kind='violin', data=tips) sns.swarmplot(x='day', y='total_bill', color='k', size=3, data=tips) # %% [markdown] # <h2>Visualizando a distribuição de um Dataset</h2> # %% [markdown] # **Histograma** # # * O método histograma tenta encontrar a melhor quantidade de bins. # %% sns.set(color_codes=True) # %% sns.distplot(tips.total_bill, kde=False) # %% [markdown] # **Plotando um histograma para uma distribuição normal** # # * Importa o Numpy para geração aleatória de dados # %% import numpy as np # %% [markdown] # * Gera 100 valores aleatórios em uma distribuição normal # %% x = np.random.normal(size=100) # %% [markdown] # * Mostra Dados aleatórios na variável **x** # %% x # %% [markdown] # * Plota o histograma para a variável **x** # %% sns.distplot(x) # %% [markdown] # * Plota o Histograma com bins=20 e KDE = True # %% sns.distplot(tips.total_bill, bins=20, kde=True) # %% [markdown] # Visualizando apenas o KDE # %% sns.distplot(tips.total_bill, hist=False) # %% [markdown] # Parâmetro RUG # %% sns.distplot(tips.total_bill, hist=False, rug=True) # %% [markdown] # <h2> Jointplot (ScatterPlot e Histograma) </h2> # # * Quando queremos ver a distribuição de duas variáveis podemos usar o Jointplot; # * União de gráficos do tipo Plot e Histogramas para as duas variáveis; # * Mostra o ScatterPlot para as duas variáveis e um Histograma para cada variável separadamente. # %% sns.jointplot(x='tip', y='total_bill', color='r', data=tips) # %% [markdown] # <h2> Hexbin Plots </h2> # # * Adequado para visualização de grande conjunto de dados; # * Tende a funcionar melhor com as cores em branco de fundo. # %% sns.jointplot(x='tip', y='total_bill', color='b', kind='hex', data=tips) # %% [markdown] # **Usando o KDE para mais de uma variável** # %% sns.jointplot(x='tip', y='total_bill', color='b', kind='kde', data=tips) # %% [markdown] # <h2>Visualizando relacionamentos emparelhados</h2> # # * Plot multiplas variáveis de um dataset; # * Cria uma matriz de eixos de mostrar a relação de cada par de colunas no dataframe; # * Por padrão plota também um histograma de cada coluna no dataframe na diagonal da matriz; # %% sns.pairplot(tips) # %% [markdown] # **Carrega o dataset iris** # %% iris = sns.load_dataset('iris') # %% iris.head() # %% [markdown] # **Plot pares emparelhando segregando pela coluna species** # %% sns.pairplot(iris, hue='species', palette='Set1') # %% [markdown] # **Plotando Scatter plots com regressão** # %% sns.pairplot(iris, kind='reg') # %% [markdown] # **Plotando histograma na diagonal** # %% sns.pairplot(iris, hue='species', diag_kind='hist') # %% [markdown] # **Plotando apenas duas colunas do dataframe** # %% sns.pairplot(iris, hue='species', vars=['sepal_width', 'sepal_length'], palette='Set1') # %% [markdown] # <h2>Gráficos de Correlação</h2> # # * Útil para visualizar se existem correlações positivas entre colunas; # * Método corr() do pandas possibilita calcular correlações por tipo *spearman* ou *pearson*; # %% correlacoes = tips.corr() # %% ax = sns.heatmap(correlacoes) # %% [markdown] # **Exibe os valores de correlação** # %% ax = sns.heatmap(correlacoes, annot=True) # %% [markdown] # **Visualizando a correlação de colunas do Dataframe Iris** # %% correlacoes = iris.corr() # %% ax = sns.heatmap(correlacoes, cmap= 'PuOr', annot= True) # %%
[ "seaborn.lmplot", "seaborn.set", "seaborn.catplot", "seaborn.heatmap", "seaborn.load_dataset", "seaborn.swarmplot", "seaborn.distplot", "numpy.random.normal", "seaborn.jointplot", "IPython.get_ipython", "seaborn.pairplot", "seaborn.stripplot" ]
[((655, 679), 'seaborn.load_dataset', 'sns.load_dataset', (['"""tips"""'], {}), "('tips')\n", (671, 679), True, 'import seaborn as sns\n'), ((1110, 1171), 'seaborn.catplot', 'sns.catplot', ([], {'x': '"""sex"""', 'kind': '"""count"""', 'palette': '"""Set2"""', 'data': 'tips'}), "(x='sex', kind='count', palette='Set2', data=tips)\n", (1121, 1171), True, 'import seaborn as sns\n'), ((1255, 1316), 'seaborn.catplot', 'sns.catplot', ([], {'y': '"""day"""', 'kind': '"""count"""', 'palette': '"""Set1"""', 'data': 'tips'}), "(y='day', kind='count', palette='Set1', data=tips)\n", (1266, 1316), True, 'import seaborn as sns\n'), ((1381, 1444), 'seaborn.catplot', 'sns.catplot', ([], {'x': '"""day"""', 'y': '"""total_bill"""', 'palette': '"""Set2"""', 'data': 'tips'}), "(x='day', y='total_bill', palette='Set2', data=tips)\n", (1392, 1444), True, 'import seaborn as sns\n'), ((1524, 1585), 'seaborn.catplot', 'sns.catplot', ([], {'x': '"""day"""', 'y': '"""total_bill"""', 'kind': '"""swarm"""', 'data': 'tips'}), "(x='day', y='total_bill', kind='swarm', data=tips)\n", (1535, 1585), True, 'import seaborn as sns\n'), ((1697, 1791), 'seaborn.catplot', 'sns.catplot', ([], {'x': '"""day"""', 'y': '"""total_bill"""', 'kind': '"""swarm"""', 'hue': '"""sex"""', 'palette': '"""Dark2"""', 'data': 'tips'}), "(x='day', y='total_bill', kind='swarm', hue='sex', palette=\n 'Dark2', data=tips)\n", (1708, 1791), True, 'import seaborn as sns\n'), ((2011, 2124), 'seaborn.catplot', 'sns.catplot', ([], {'x': '"""day"""', 'y': '"""total_bill"""', 'kind': '"""swarm"""', 'hue': '"""sex"""', 'order': "['Sat', 'Sun', 'Fri', 'Thur']", 'data': 'tips'}), "(x='day', y='total_bill', kind='swarm', hue='sex', order=['Sat',\n 'Sun', 'Fri', 'Thur'], data=tips)\n", (2022, 2124), True, 'import seaborn as sns\n'), ((2199, 2260), 'seaborn.catplot', 'sns.catplot', ([], {'x': '"""total_bill"""', 'y': '"""day"""', 'kind': '"""swarm"""', 'data': 'tips'}), "(x='total_bill', y='day', kind='swarm', data=tips)\n", (2210, 2260), True, 'import seaborn as sns\n'), ((2761, 2837), 'seaborn.lmplot', 'sns.lmplot', ([], {'x': '"""total_bill"""', 'y': '"""tip"""', 'hue': '"""sex"""', 'palette': '"""Pastel1"""', 'data': 'tips'}), "(x='total_bill', y='tip', hue='sex', palette='Pastel1', data=tips)\n", (2771, 2837), True, 'import seaborn as sns\n'), ((3009, 3102), 'seaborn.lmplot', 'sns.lmplot', ([], {'x': '"""total_bill"""', 'y': '"""tip"""', 'hue': '"""smoker"""', 'col': '"""time"""', 'palette': '"""Set2"""', 'data': 'tips'}), "(x='total_bill', y='tip', hue='smoker', col='time', palette=\n 'Set2', data=tips)\n", (3019, 3102), True, 'import seaborn as sns\n'), ((3214, 3364), 'seaborn.lmplot', 'sns.lmplot', ([], {'x': '"""total_bill"""', 'y': '"""tip"""', 'hue': '"""smoker"""', 'col': '"""time"""', 'palette': '"""Set1"""', 'data': 'tips', 'scatter_kws': "{'s': 90, 'alpha': 0.5}", 'line_kws': "{'lw': 4}"}), "(x='total_bill', y='tip', hue='smoker', col='time', palette=\n 'Set1', data=tips, scatter_kws={'s': 90, 'alpha': 0.5}, line_kws={'lw': 4})\n", (3224, 3364), True, 'import seaborn as sns\n'), ((3513, 3616), 'seaborn.lmplot', 'sns.lmplot', ([], {'x': '"""total_bill"""', 'y': '"""tip"""', 'hue': '"""smoker"""', 'col': '"""time"""', 'row': '"""sex"""', 'palette': '"""Set2"""', 'data': 'tips'}), "(x='total_bill', y='tip', hue='smoker', col='time', row='sex',\n palette='Set2', data=tips)\n", (3523, 3616), True, 'import seaborn as sns\n'), ((4083, 4142), 'seaborn.catplot', 'sns.catplot', ([], {'x': '"""day"""', 'y': '"""total_bill"""', 'kind': '"""box"""', 'data': 'tips'}), "(x='day', y='total_bill', kind='box', data=tips)\n", (4094, 4142), True, 'import seaborn as sns\n'), ((4250, 4323), 'seaborn.catplot', 'sns.catplot', ([], {'x': '"""day"""', 'y': '"""total_bill"""', 'hue': '"""smoker"""', 'kind': '"""box"""', 'data': 'tips'}), "(x='day', y='total_bill', hue='smoker', kind='box', data=tips)\n", (4261, 4323), True, 'import seaborn as sns\n'), ((4501, 4562), 'seaborn.catplot', 'sns.catplot', ([], {'x': '"""day"""', 'y': '"""total_bill"""', 'kind': '"""boxen"""', 'data': 'tips'}), "(x='day', y='total_bill', kind='boxen', data=tips)\n", (4512, 4562), True, 'import seaborn as sns\n'), ((4726, 4787), 'seaborn.catplot', 'sns.catplot', ([], {'x': '"""day"""', 'y': '"""total_bill"""', 'kind': '"""boxen"""', 'data': 'tips'}), "(x='day', y='total_bill', kind='boxen', data=tips)\n", (4737, 4787), True, 'import seaborn as sns\n'), ((4788, 4851), 'seaborn.stripplot', 'sns.stripplot', ([], {'x': '"""day"""', 'y': '"""total_bill"""', 'data': 'tips', 'color': '"""blue"""'}), "(x='day', y='total_bill', data=tips, color='blue')\n", (4801, 4851), True, 'import seaborn as sns\n'), ((5034, 5135), 'seaborn.catplot', 'sns.catplot', ([], {'x': '"""sex"""', 'y': '"""total_bill"""', 'hue': '"""smoker"""', 'col': '"""time"""', 'data': 'tips', 'kind': '"""boxen"""', 'height': '(4)'}), "(x='sex', y='total_bill', hue='smoker', col='time', data=tips,\n kind='boxen', height=4)\n", (5045, 5135), True, 'import seaborn as sns\n'), ((5431, 5493), 'seaborn.catplot', 'sns.catplot', ([], {'x': '"""day"""', 'y': '"""total_bill"""', 'kind': '"""violin"""', 'data': 'tips'}), "(x='day', y='total_bill', kind='violin', data=tips)\n", (5442, 5493), True, 'import seaborn as sns\n'), ((5541, 5603), 'seaborn.catplot', 'sns.catplot', ([], {'x': '"""total_bill"""', 'y': '"""day"""', 'kind': '"""violin"""', 'data': 'tips'}), "(x='total_bill', y='day', kind='violin', data=tips)\n", (5552, 5603), True, 'import seaborn as sns\n'), ((5687, 5761), 'seaborn.catplot', 'sns.catplot', ([], {'x': '"""day"""', 'y': '"""total_bill"""', 'hue': '"""time"""', 'kind': '"""violin"""', 'data': 'tips'}), "(x='day', y='total_bill', hue='time', kind='violin', data=tips)\n", (5698, 5761), True, 'import seaborn as sns\n'), ((5914, 6003), 'seaborn.catplot', 'sns.catplot', ([], {'x': '"""day"""', 'y': '"""total_bill"""', 'hue': '"""sex"""', 'split': '(True)', 'kind': '"""violin"""', 'data': 'tips'}), "(x='day', y='total_bill', hue='sex', split=True, kind='violin',\n data=tips)\n", (5925, 6003), True, 'import seaborn as sns\n'), ((6176, 6298), 'seaborn.catplot', 'sns.catplot', ([], {'x': '"""day"""', 'y': '"""total_bill"""', 'hue': '"""sex"""', 'split': '(True)', 'inner': '"""stick"""', 'palette': '"""pastel"""', 'kind': '"""violin"""', 'data': 'tips'}), "(x='day', y='total_bill', hue='sex', split=True, inner='stick',\n palette='pastel', kind='violin', data=tips)\n", (6187, 6298), True, 'import seaborn as sns\n'), ((6490, 6598), 'seaborn.catplot', 'sns.catplot', ([], {'x': '"""day"""', 'y': '"""total_bill"""', 'hue': '"""sex"""', 'split': '(True)', 'palette': '"""pastel"""', 'kind': '"""violin"""', 'data': 'tips'}), "(x='day', y='total_bill', hue='sex', split=True, palette=\n 'pastel', kind='violin', data=tips)\n", (6501, 6598), True, 'import seaborn as sns\n'), ((6594, 6662), 'seaborn.swarmplot', 'sns.swarmplot', ([], {'x': '"""day"""', 'y': '"""total_bill"""', 'color': '"""k"""', 'size': '(3)', 'data': 'tips'}), "(x='day', y='total_bill', color='k', size=3, data=tips)\n", (6607, 6662), True, 'import seaborn as sns\n'), ((6844, 6869), 'seaborn.set', 'sns.set', ([], {'color_codes': '(True)'}), '(color_codes=True)\n', (6851, 6869), True, 'import seaborn as sns\n'), ((6877, 6917), 'seaborn.distplot', 'sns.distplot', (['tips.total_bill'], {'kde': '(False)'}), '(tips.total_bill, kde=False)\n', (6889, 6917), True, 'import seaborn as sns\n'), ((7159, 7185), 'numpy.random.normal', 'np.random.normal', ([], {'size': '(100)'}), '(size=100)\n', (7175, 7185), True, 'import numpy as np\n'), ((7325, 7340), 'seaborn.distplot', 'sns.distplot', (['x'], {}), '(x)\n', (7337, 7340), True, 'import seaborn as sns\n'), ((7412, 7460), 'seaborn.distplot', 'sns.distplot', (['tips.total_bill'], {'bins': '(20)', 'kde': '(True)'}), '(tips.total_bill, bins=20, kde=True)\n', (7424, 7460), True, 'import seaborn as sns\n'), ((7512, 7553), 'seaborn.distplot', 'sns.distplot', (['tips.total_bill'], {'hist': '(False)'}), '(tips.total_bill, hist=False)\n', (7524, 7553), True, 'import seaborn as sns\n'), ((7593, 7644), 'seaborn.distplot', 'sns.distplot', (['tips.total_bill'], {'hist': '(False)', 'rug': '(True)'}), '(tips.total_bill, hist=False, rug=True)\n', (7605, 7644), True, 'import seaborn as sns\n'), ((7975, 8035), 'seaborn.jointplot', 'sns.jointplot', ([], {'x': '"""tip"""', 'y': '"""total_bill"""', 'color': '"""r"""', 'data': 'tips'}), "(x='tip', y='total_bill', color='r', data=tips)\n", (7988, 8035), True, 'import seaborn as sns\n'), ((8210, 8282), 'seaborn.jointplot', 'sns.jointplot', ([], {'x': '"""tip"""', 'y': '"""total_bill"""', 'color': '"""b"""', 'kind': '"""hex"""', 'data': 'tips'}), "(x='tip', y='total_bill', color='b', kind='hex', data=tips)\n", (8223, 8282), True, 'import seaborn as sns\n'), ((8351, 8423), 'seaborn.jointplot', 'sns.jointplot', ([], {'x': '"""tip"""', 'y': '"""total_bill"""', 'color': '"""b"""', 'kind': '"""kde"""', 'data': 'tips'}), "(x='tip', y='total_bill', color='b', kind='kde', data=tips)\n", (8364, 8423), True, 'import seaborn as sns\n'), ((8727, 8745), 'seaborn.pairplot', 'sns.pairplot', (['tips'], {}), '(tips)\n', (8739, 8745), True, 'import seaborn as sns\n'), ((8805, 8829), 'seaborn.load_dataset', 'sns.load_dataset', (['"""iris"""'], {}), "('iris')\n", (8821, 8829), True, 'import seaborn as sns\n'), ((8933, 8982), 'seaborn.pairplot', 'sns.pairplot', (['iris'], {'hue': '"""species"""', 'palette': '"""Set1"""'}), "(iris, hue='species', palette='Set1')\n", (8945, 8982), True, 'import seaborn as sns\n'), ((9049, 9079), 'seaborn.pairplot', 'sns.pairplot', (['iris'], {'kind': '"""reg"""'}), "(iris, kind='reg')\n", (9061, 9079), True, 'import seaborn as sns\n'), ((9141, 9192), 'seaborn.pairplot', 'sns.pairplot', (['iris'], {'hue': '"""species"""', 'diag_kind': '"""hist"""'}), "(iris, hue='species', diag_kind='hist')\n", (9153, 9192), True, 'import seaborn as sns\n'), ((9264, 9355), 'seaborn.pairplot', 'sns.pairplot', (['iris'], {'hue': '"""species"""', 'vars': "['sepal_width', 'sepal_length']", 'palette': '"""Set1"""'}), "(iris, hue='species', vars=['sepal_width', 'sepal_length'],\n palette='Set1')\n", (9276, 9355), True, 'import seaborn as sns\n'), ((9618, 9642), 'seaborn.heatmap', 'sns.heatmap', (['correlacoes'], {}), '(correlacoes)\n', (9629, 9642), True, 'import seaborn as sns\n'), ((9708, 9744), 'seaborn.heatmap', 'sns.heatmap', (['correlacoes'], {'annot': '(True)'}), '(correlacoes, annot=True)\n', (9719, 9744), True, 'import seaborn as sns\n'), ((9867, 9916), 'seaborn.heatmap', 'sns.heatmap', (['correlacoes'], {'cmap': '"""PuOr"""', 'annot': '(True)'}), "(correlacoes, cmap='PuOr', annot=True)\n", (9878, 9916), True, 'import seaborn as sns\n'), ((2708, 2721), 'IPython.get_ipython', 'get_ipython', ([], {}), '()\n', (2719, 2721), False, 'from IPython import get_ipython\n'), ((2956, 2969), 'IPython.get_ipython', 'get_ipython', ([], {}), '()\n', (2967, 2969), False, 'from IPython import get_ipython\n'), ((3161, 3174), 'IPython.get_ipython', 'get_ipython', ([], {}), '()\n', (3172, 3174), False, 'from IPython import get_ipython\n'), ((3460, 3473), 'IPython.get_ipython', 'get_ipython', ([], {}), '()\n', (3471, 3473), False, 'from IPython import get_ipython\n'), ((4981, 4994), 'IPython.get_ipython', 'get_ipython', ([], {}), '()\n', (4992, 4994), False, 'from IPython import get_ipython\n')]
# -*- coding: utf-8 -*- """Recommender_System.ipynb Automatically generated by Colaboratory. Original file is located at https://colab.research.google.com/drive/1_yvJ9w2fZE6sxmTSjig7LhQhWl0HOG8p # Importing data and lemmatizing the data """ import numpy as np import pandas as pd import re import scipy import math URL = 'https://drive.google.com/file/d/137eW4F35OctoRuq5DasVUXw6GpmfXdBS/view?usp=sharing' path = 'https://drive.google.com/uc?export=download&id='+URL.split('/')[-2] #df = pd.read_pickle(path) data = pd.read_csv(path, skip_blank_lines=True) pd.set_option('display.max_colwidth', None) print(data.shape) data.drop_duplicates(subset='content', inplace=True, ignore_index=True) data.shape data.head(1) data[data['_id'] == '6076fadb0b3e8bc9b779293e']['_id'].to_string() def make_lower_case(text): return text.lower() import re from pprint import pprint import nltk, spacy, gensim from sklearn.feature_extraction.text import CountVectorizer def get_lemmatized_clean_data(df): # Convert to list data = df.content.tolist() # Remove Emails data = [re.sub('\S*@\S*\s?', '', sent) for sent in data] # Remove new line characters data = [re.sub('\s+', ' ', sent) for sent in data] # Remove distracting single quotes data = [re.sub("\'", "", sent) for sent in data] # pprint(data[:1]) def sent_to_words(sentences): for sentence in sentences: yield(gensim.utils.simple_preprocess(str(sentence), deacc=True)) # deacc=True removes punctuations data_words = list(sent_to_words(data)) # print(data_words[:1]) def lemmatization(texts, allowed_postags=['NOUN', 'ADJ', 'VERB', 'ADV']): """https://spacy.io/api/annotation""" texts_out = [] for sent in texts: doc = nlp(" ".join(sent)) texts_out.append(" ".join([token.lemma_ if token.lemma_ not in ['-PRON-'] else '' for token in doc if token.pos_ in allowed_postags])) return texts_out # Initialize spacy 'en' model, keeping only tagger component (for efficiency) # Run in terminal: python3 -m spacy download en nlp = spacy.load('en_core_web_sm', disable=['parser', 'ner']) # Do lemmatization keeping only Noun, Adj, Verb, Adverb data_lemmatized = lemmatization(data_words, allowed_postags=['NOUN', 'ADJ', 'VERB', 'ADV']) return data_lemmatized X = get_lemmatized_clean_data(data) max_time = [] for i in X: max_time.append(len(i.split(' '))/2.5) data['Max_Time'] = max_time data.head() """# SKlearn NewsData Import""" from sklearn.datasets import fetch_20newsgroups newsgroups_train = fetch_20newsgroups(subset='train') def get_data(mydata): mydata.keys() df = pd.DataFrame([mydata['data'],[mydata['target_names'][idx] for idx in mydata['target']],mydata['target']]) df = df.transpose() df.columns = ['content', 'target_names', 'target'] return df df = get_data(newsgroups_train) df.head() news = data.drop(axis = 1, columns=['_id', 'y',]).to_numpy() data_lemmatized = get_lemmatized_clean_data(df) df.head() """# Converting the data to bag_of_word representation""" import nltk nltk.download('stopwords') from nltk.corpus import stopwords my_stopwords = stopwords.words('english') from sklearn.feature_extraction.text import TfidfVectorizer, CountVectorizer from sklearn.decomposition import TruncatedSVD vectorizor = TfidfVectorizer(stop_words=my_stopwords, lowercase= True) bag_of_words = vectorizor.fit_transform(X) """# Content Based Similarity Using TFIDF Vector""" from numpy import dot from numpy.linalg import norm def similarity(a,b): cos_sim = dot(a, b)/(norm(a)*norm(b)) return cos_sim def ContentBasedFiltering(id, first_n = 10): similarity_dic = {} news_index = data[data['_id']==id].index[0] for i in data['_id']: an_index = data[data['_id']==i].index[0] a = np.array(bag_of_words[news_index].todense())[0] b = np.array(bag_of_words[an_index].todense())[0] similarity_dic[i] = similarity(a, b) sorted_most_similar = sorted(similarity_dic.items(), key = lambda kv:(kv[1], kv[0]), reverse=True) return sorted_most_similar[:first_n] ContentBasedFiltering('6076fadb0b3e8bc9b779293e') for keys in ContentBasedFiltering('6076fadb0b3e8bc9b779293e'): print(data[data['_id'] == keys[0]]['title']) """# Content Based Similarity Using SVD """ # Performing SVD svd = TruncatedSVD(n_components=50) lsa = svd.fit_transform(bag_of_words) def SVDContentBasedFiltering(id, first_n = 10): similarity_dic = {} news_index = data[data['_id']==id].index[0] for i in data['_id']: an_index = data[data['_id']==i].index[0] a = np.array(lsa[news_index]) b = np.array(lsa[an_index]) similarity_dic[i] = similarity(a, b) sorted_most_similar = sorted(similarity_dic.items(), key = lambda kv:(kv[1], kv[0]), reverse=True) return sorted_most_similar[:first_n] SVDContentBasedFiltering('6076fadb0b3e8bc9b779293e') for keys in SVDContentBasedFiltering('6076fadb0b3e8bc9b779293e'): print(data[data['_id'] == keys[0]]['title']) """# LDA Implementation """ from sklearn.decomposition import LatentDirichletAllocation from sklearn.model_selection import GridSearchCV lda = LatentDirichletAllocation(learning_method='batch', n_jobs=-1) bag_of_words.T # LDA Cross-Validation n_components = [20, 50, 70] learning_decay = [0.5, 0.7, 0.8] params = {'n_components': n_components, 'learning_decay': learning_decay} model = GridSearchCV(lda, param_grid=params) model.fit(bag_of_words.T) best_params = model.best_estimator_ best_params lda_res = best_params.components_.T lda_res.shape import pickle pickle_file = 'lda_cross_validation_rev.pkl' with open(pickle_file, 'wb') as file: pickle.dump(model, file) from pydrive.auth import GoogleAuth from pydrive.drive import GoogleDrive from google.colab import auth from oauth2client.client import GoogleCredentials # 1. Authenticate and create the PyDrive client. auth.authenticate_user() gauth = GoogleAuth() gauth.credentials = GoogleCredentials.get_application_default() drive = GoogleDrive(gauth) # get the folder id where you want to save your file file = drive.CreateFile({'parents':[{u'id': '19AI35wfuabh1JQ6b1Z3YH5uJ6uL3N6BD'}]}) file.SetContentFile(pickle_file) file.Upload() with open(pickle_file, 'rb') as file: lda_pkl_model = pickle.load(file) def LDAContentBasedFiltering(id, first_n = 10): similarity_dic = {} news_index = data[data['_id']==id].index[0] for i in data['_id']: an_index = data[data['_id']==i].index[0] a = np.array(lda_res[news_index]) b = np.array(lda_res[an_index]) similarity_dic[i] = similarity(a, b) sorted_most_similar = sorted(similarity_dic.items(), key = lambda kv:(kv[1], kv[0]), reverse=True) return sorted_most_similar[:first_n] LDAContentBasedFiltering('6076fadb0b3e8bc9b779293e') for keys in LDAContentBasedFiltering('6076fadb0b3e8bc9b779293e'): print(data[data['_id'] == keys[0]]['title']) """# Word embedding using Glove Vectorizor""" from google.colab import drive drive.mount('/content/drive') from numpy import array from numpy import asarray from numpy import zeros embeddings_dictionary = dict() glove_file = open('/content/drive/MyDrive/NLP and Text Analysis/glove.6B/glove.6B.100d.txt', encoding="utf8") for line in glove_file: records = line.split() word = records[0] vector_dimensions = asarray(records[1:], dtype='float32') embeddings_dictionary[word] = vector_dimensions glove_file.close() i = 0 glov_stop = [] news_embedding_dict = dict() for word in vectorizor.vocabulary_.keys(): if word in embeddings_dictionary: news_embedding_dict[word] = embeddings_dictionary[word] else: glov_stop.append(word) stopset = set(nltk.corpus.stopwords.words('english')) new_stopwords_list = stopset.union(glov_stop) vectorizor_glov = TfidfVectorizer(stop_words=new_stopwords_list) glov_bag_of_words = vectorizor_glov.fit_transform(X) y = np.array([val for (key, val) in news_embedding_dict.items()]) y.shape glov_bag_of_words.shape document_embedding = glov_bag_of_words*y document_embedding.shape document_embedding def ContentBasedFilteringWordEmbedding(id, first_n = 10): similarity_dic = {} news_index = data[data['_id']==id].index[0] for i in data['_id']: an_index = data[data['_id']==i].index[0] a = np.array(document_embedding[news_index]) b = np.array(document_embedding[an_index]) similarity_dic[i] = similarity(a, b) sorted_most_similar = sorted(similarity_dic.items(), key = lambda kv:(kv[1], kv[0]), reverse=True) return sorted_most_similar[:first_n] ContentBasedFilteringWordEmbedding('6076fadb0b3e8bc9b779293e') """# Collaborative Filtering""" topics = ['cricket', 'football', 'golf', 'asia', 'africa', 'europe', 'americas', 'style', 'tech', 'science', 'hollywood', 'us politics', 'stock market', 'travel', 'coronavirus', 'black lives matter'] from random import sample class User: def __init__(self, id): self.id = id self.prefered_categories = sample(topics, np.random.randint(low=3, high= 5)) self.no_of_articles_served = np.random.randint(10, 50)*10 self.no_of_sessions = math.ceil((self.no_of_articles_served)/10) self.ids = [self.id for _ in range(self.no_of_articles_served)] self.sessions = [] self.articles_served = [] self.ratings = [] self.click = [] self.ranks = [] j = math.ceil(self.no_of_articles_served*0.7) for m in range(j): id_temp = np.random.choice(data[data['topics'].isin(self.prefered_categories)]['_id']) self.articles_served.append(id_temp) click = np.random.binomial(1, 0.7,1)[0] self.click.append(click) self.ratings.append('-' if click == 0 else np.random.randint((data[data['_id'] == id_temp]['Max_Time'])/4, data[data['_id'] == self.articles_served[m]]['Max_Time'])[0]) j = self.no_of_articles_served-j for m in range(j): id_temp = np.random.choice(data[~data['topics'].isin(self.prefered_categories)]['_id']) self.articles_served.append(id_temp) click = np.random.binomial(1, 0.1,1)[0] self.click.append(click) self.ratings.append('-' if click == 0 else np.random.randint(0, data[data['_id'] == id_temp]['Max_Time'])[0]) for i in range(self.no_of_sessions): for k in range(10): self.sessions.append(i) self.ranks.append(k) new_user = User(1) data[data['_id'].isin(new_user.articles_served)].tail(10) def CreateRandomUserProfiler(max_no_user = 40): Users = [] for i in range(max_no_user): Users.append(User(i)) print(Users[i-1].prefered_categories) UserProfiler = pd.DataFrame(columns=['UserId', 'SessionID', 'ArticleID Served', 'Article Rank', 'Click', 'Time Spent']) for user in Users: df = pd.DataFrame() df['UserId'] = user.ids df['SessionID'] = user.sessions df['ArticleID Served'] = user.articles_served df['Article Rank'] = user.ranks df['Click'] = user.click df['Time Spent'] = user.ratings UserProfiler = pd.concat([UserProfiler,df], ignore_index=True) return UserProfiler UserProfiler = CreateRandomUserProfiler(40) UserProfiler.head() UserProfiler.shape """# Matrix Factorization""" def getNewsInfo(id): return data[data['_id']==id] import numpy as np from scipy.sparse import csr_matrix # Creating a user * news sparse matrix sparseMatrix = csr_matrix((UserProfiler.UserId.unique().shape[0], data.shape[0])).toarray() k = 0 user = UserProfiler.iloc[k] for i in UserProfiler.UserId.unique(): while user.UserId == i and k < UserProfiler.shape[0]: user = UserProfiler.iloc[k] if user.Click: newsInfo = getNewsInfo(user['ArticleID Served']) rating = user['Time Spent']/newsInfo['Max_Time'] sparseMatrix[i][newsInfo.index] = rating k+=1 userItem = csr_matrix(sparseMatrix) from numpy import count_nonzero sparsity = 1.0 - count_nonzero(sparseMatrix) / sparseMatrix.size print(sparsity) pd.DataFrame(sparseMatrix) def MF(X, num_dims, step_size,epochs,thres,lam_da): P = scipy.sparse.rand(X.shape[0], num_dims, 1, format='csr') P = scipy.sparse.csr_matrix(P/scipy.sparse.csr_matrix.sum(P, axis=1)) Q = scipy.sparse.rand(num_dims, X.shape[1], 1, format='csr') Q = scipy.sparse.csr_matrix(Q/ scipy.sparse.csr_matrix.sum(Q, axis=0)) prev_error = 0 for iterat in range(epochs): errors = X - make_sparse(P.dot(Q).todense(), X) mse = np.sum(errors.multiply(errors))/len(X.indices) P_new=P + step_size*2*(errors.dot(Q.T)-lam_da*P) Q_new=Q + step_size*2*(P.T.dot(errors)-lam_da*Q) P=P_new Q=Q_new prev_error=mse #if iterat%1==0: print(iterat,mse) return pd.DataFrame(np.array(P.dot(Q).todense())) def make_sparse(array, X): array = np.array(array) x_pos, y_pos = X.nonzero() # print(x_pos, y_pos) try2 = np.array([[0 for i in range(array.shape[1])] for j in range(array.shape[0])]) l = len(x_pos) for i in range(l): # print(x_pos[i], y_pos[i]) try2[x_pos[i]][y_pos[i]] = array[x_pos[i]][y_pos[i]] return scipy.sparse.csr_matrix(try2) UserItem_MF = MF(userItem, 2, 0.005, 500, 0.00001, 5) def GetRecommendations(UserID, top_n = 10): userRating = UserItem_MF[UserID] s = numpy.array(userRating) sort_index = numpy.argsort(s) print(sort_index) print('Last n topics',data.iloc[sort_index[-top_n:]]['topics']) print('First n topics',data.iloc[sort_index[:top_n]]['topics']) recommended_ids = data.iloc[sort_index[-top_n:]]['_id'] return recommended_ids ids = GetRecommendations(1) for id in ids: print(getNewsInfo(id)) """# Implementing Flask API""" from flask import Flask from flask_ngrok import run_with_ngrok app = Flask(__name__) run_with_ngrok(app) @app.route("/") def home(): return "<h1>GFG is great platform to learn</h1>" app.run() import numpy s = numpy.array([2, 3, 1, 4, 5]) sort_index = numpy.argsort(s) print(sort_index)
[ "google.colab.drive.CreateFile", "sklearn.model_selection.GridSearchCV", "pickle.dump", "pandas.read_csv", "sklearn.feature_extraction.text.TfidfVectorizer", "numpy.argsort", "pickle.load", "sklearn.decomposition.LatentDirichletAllocation", "numpy.linalg.norm", "numpy.random.randint", "pydrive.d...
[((525, 565), 'pandas.read_csv', 'pd.read_csv', (['path'], {'skip_blank_lines': '(True)'}), '(path, skip_blank_lines=True)\n', (536, 565), True, 'import pandas as pd\n'), ((566, 609), 'pandas.set_option', 'pd.set_option', (['"""display.max_colwidth"""', 'None'], {}), "('display.max_colwidth', None)\n", (579, 609), True, 'import pandas as pd\n'), ((2626, 2660), 'sklearn.datasets.fetch_20newsgroups', 'fetch_20newsgroups', ([], {'subset': '"""train"""'}), "(subset='train')\n", (2644, 2660), False, 'from sklearn.datasets import fetch_20newsgroups\n'), ((3152, 3178), 'nltk.download', 'nltk.download', (['"""stopwords"""'], {}), "('stopwords')\n", (3165, 3178), False, 'import nltk\n'), ((3228, 3254), 'nltk.corpus.stopwords.words', 'stopwords.words', (['"""english"""'], {}), "('english')\n", (3243, 3254), False, 'from nltk.corpus import stopwords\n'), ((3394, 3450), 'sklearn.feature_extraction.text.TfidfVectorizer', 'TfidfVectorizer', ([], {'stop_words': 'my_stopwords', 'lowercase': '(True)'}), '(stop_words=my_stopwords, lowercase=True)\n', (3409, 3450), False, 'from sklearn.feature_extraction.text import TfidfVectorizer, CountVectorizer\n'), ((4405, 4434), 'sklearn.decomposition.TruncatedSVD', 'TruncatedSVD', ([], {'n_components': '(50)'}), '(n_components=50)\n', (4417, 4434), False, 'from sklearn.decomposition import TruncatedSVD\n'), ((5238, 5299), 'sklearn.decomposition.LatentDirichletAllocation', 'LatentDirichletAllocation', ([], {'learning_method': '"""batch"""', 'n_jobs': '(-1)'}), "(learning_method='batch', n_jobs=-1)\n", (5263, 5299), False, 'from sklearn.decomposition import LatentDirichletAllocation\n'), ((5486, 5522), 'sklearn.model_selection.GridSearchCV', 'GridSearchCV', (['lda'], {'param_grid': 'params'}), '(lda, param_grid=params)\n', (5498, 5522), False, 'from sklearn.model_selection import GridSearchCV\n'), ((5986, 6010), 'google.colab.auth.authenticate_user', 'auth.authenticate_user', ([], {}), '()\n', (6008, 6010), False, 'from google.colab import auth\n'), ((6019, 6031), 'pydrive.auth.GoogleAuth', 'GoogleAuth', ([], {}), '()\n', (6029, 6031), False, 'from pydrive.auth import GoogleAuth\n'), ((6052, 6095), 'oauth2client.client.GoogleCredentials.get_application_default', 'GoogleCredentials.get_application_default', ([], {}), '()\n', (6093, 6095), False, 'from oauth2client.client import GoogleCredentials\n'), ((6104, 6122), 'pydrive.drive.GoogleDrive', 'GoogleDrive', (['gauth'], {}), '(gauth)\n', (6115, 6122), False, 'from pydrive.drive import GoogleDrive\n'), ((6186, 6263), 'google.colab.drive.CreateFile', 'drive.CreateFile', (["{'parents': [{u'id': '19AI35wfuabh1JQ6b1Z3YH5uJ6uL3N6BD'}]}"], {}), "({'parents': [{u'id': '19AI35wfuabh1JQ6b1Z3YH5uJ6uL3N6BD'}]})\n", (6202, 6263), False, 'from google.colab import drive\n'), ((7095, 7124), 'google.colab.drive.mount', 'drive.mount', (['"""/content/drive"""'], {}), "('/content/drive')\n", (7106, 7124), False, 'from google.colab import drive\n'), ((7894, 7940), 'sklearn.feature_extraction.text.TfidfVectorizer', 'TfidfVectorizer', ([], {'stop_words': 'new_stopwords_list'}), '(stop_words=new_stopwords_list)\n', (7909, 7940), False, 'from sklearn.feature_extraction.text import TfidfVectorizer, CountVectorizer\n'), ((11867, 11891), 'scipy.sparse.csr_matrix', 'csr_matrix', (['sparseMatrix'], {}), '(sparseMatrix)\n', (11877, 11891), False, 'from scipy.sparse import csr_matrix\n'), ((12005, 12031), 'pandas.DataFrame', 'pd.DataFrame', (['sparseMatrix'], {}), '(sparseMatrix)\n', (12017, 12031), True, 'import pandas as pd\n'), ((13730, 13745), 'flask.Flask', 'Flask', (['__name__'], {}), '(__name__)\n', (13735, 13745), False, 'from flask import Flask\n'), ((13746, 13765), 'flask_ngrok.run_with_ngrok', 'run_with_ngrok', (['app'], {}), '(app)\n', (13760, 13765), False, 'from flask_ngrok import run_with_ngrok\n'), ((13886, 13914), 'numpy.array', 'numpy.array', (['[2, 3, 1, 4, 5]'], {}), '([2, 3, 1, 4, 5])\n', (13897, 13914), False, 'import numpy\n'), ((13928, 13944), 'numpy.argsort', 'numpy.argsort', (['s'], {}), '(s)\n', (13941, 13944), False, 'import numpy\n'), ((2137, 2192), 'spacy.load', 'spacy.load', (['"""en_core_web_sm"""'], {'disable': "['parser', 'ner']"}), "('en_core_web_sm', disable=['parser', 'ner'])\n", (2147, 2192), False, 'import nltk, spacy, gensim\n'), ((2711, 2822), 'pandas.DataFrame', 'pd.DataFrame', (["[mydata['data'], [mydata['target_names'][idx] for idx in mydata['target']],\n mydata['target']]"], {}), "([mydata['data'], [mydata['target_names'][idx] for idx in\n mydata['target']], mydata['target']])\n", (2723, 2822), True, 'import pandas as pd\n'), ((5756, 5780), 'pickle.dump', 'pickle.dump', (['model', 'file'], {}), '(model, file)\n', (5767, 5780), False, 'import pickle\n'), ((6371, 6388), 'pickle.load', 'pickle.load', (['file'], {}), '(file)\n', (6382, 6388), False, 'import pickle\n'), ((7441, 7478), 'numpy.asarray', 'asarray', (['records[1:]'], {'dtype': '"""float32"""'}), "(records[1:], dtype='float32')\n", (7448, 7478), False, 'from numpy import asarray\n'), ((7790, 7828), 'nltk.corpus.stopwords.words', 'nltk.corpus.stopwords.words', (['"""english"""'], {}), "('english')\n", (7817, 7828), False, 'import nltk\n'), ((10693, 10801), 'pandas.DataFrame', 'pd.DataFrame', ([], {'columns': "['UserId', 'SessionID', 'ArticleID Served', 'Article Rank', 'Click',\n 'Time Spent']"}), "(columns=['UserId', 'SessionID', 'ArticleID Served',\n 'Article Rank', 'Click', 'Time Spent'])\n", (10705, 10801), True, 'import pandas as pd\n'), ((12091, 12147), 'scipy.sparse.rand', 'scipy.sparse.rand', (['X.shape[0]', 'num_dims', '(1)'], {'format': '"""csr"""'}), "(X.shape[0], num_dims, 1, format='csr')\n", (12108, 12147), False, 'import scipy\n'), ((12226, 12282), 'scipy.sparse.rand', 'scipy.sparse.rand', (['num_dims', 'X.shape[1]', '(1)'], {'format': '"""csr"""'}), "(num_dims, X.shape[1], 1, format='csr')\n", (12243, 12282), False, 'import scipy\n'), ((12801, 12816), 'numpy.array', 'np.array', (['array'], {}), '(array)\n', (12809, 12816), True, 'import numpy as np\n'), ((13094, 13123), 'scipy.sparse.csr_matrix', 'scipy.sparse.csr_matrix', (['try2'], {}), '(try2)\n', (13117, 13123), False, 'import scipy\n'), ((13265, 13288), 'numpy.array', 'numpy.array', (['userRating'], {}), '(userRating)\n', (13276, 13288), False, 'import numpy\n'), ((13304, 13320), 'numpy.argsort', 'numpy.argsort', (['s'], {}), '(s)\n', (13317, 13320), False, 'import numpy\n'), ((1092, 1125), 're.sub', 're.sub', (['"""\\\\S*@\\\\S*\\\\s?"""', '""""""', 'sent'], {}), "('\\\\S*@\\\\S*\\\\s?', '', sent)\n", (1098, 1125), False, 'import re\n'), ((1187, 1212), 're.sub', 're.sub', (['"""\\\\s+"""', '""" """', 'sent'], {}), "('\\\\s+', ' ', sent)\n", (1193, 1212), False, 'import re\n'), ((1282, 1303), 're.sub', 're.sub', (['"""\'"""', '""""""', 'sent'], {}), '("\'", \'\', sent)\n', (1288, 1303), False, 'import re\n'), ((3635, 3644), 'numpy.dot', 'dot', (['a', 'b'], {}), '(a, b)\n', (3638, 3644), False, 'from numpy import dot\n'), ((4667, 4692), 'numpy.array', 'np.array', (['lsa[news_index]'], {}), '(lsa[news_index])\n', (4675, 4692), True, 'import numpy as np\n'), ((4701, 4724), 'numpy.array', 'np.array', (['lsa[an_index]'], {}), '(lsa[an_index])\n', (4709, 4724), True, 'import numpy as np\n'), ((6583, 6612), 'numpy.array', 'np.array', (['lda_res[news_index]'], {}), '(lda_res[news_index])\n', (6591, 6612), True, 'import numpy as np\n'), ((6621, 6648), 'numpy.array', 'np.array', (['lda_res[an_index]'], {}), '(lda_res[an_index])\n', (6629, 6648), True, 'import numpy as np\n'), ((8388, 8428), 'numpy.array', 'np.array', (['document_embedding[news_index]'], {}), '(document_embedding[news_index])\n', (8396, 8428), True, 'import numpy as np\n'), ((8437, 8475), 'numpy.array', 'np.array', (['document_embedding[an_index]'], {}), '(document_embedding[an_index])\n', (8445, 8475), True, 'import numpy as np\n'), ((9223, 9265), 'math.ceil', 'math.ceil', (['(self.no_of_articles_served / 10)'], {}), '(self.no_of_articles_served / 10)\n', (9232, 9265), False, 'import math\n'), ((9457, 9500), 'math.ceil', 'math.ceil', (['(self.no_of_articles_served * 0.7)'], {}), '(self.no_of_articles_served * 0.7)\n', (9466, 9500), False, 'import math\n'), ((10828, 10842), 'pandas.DataFrame', 'pd.DataFrame', ([], {}), '()\n', (10840, 10842), True, 'import pandas as pd\n'), ((11077, 11125), 'pandas.concat', 'pd.concat', (['[UserProfiler, df]'], {'ignore_index': '(True)'}), '([UserProfiler, df], ignore_index=True)\n', (11086, 11125), True, 'import pandas as pd\n'), ((11941, 11968), 'numpy.count_nonzero', 'count_nonzero', (['sparseMatrix'], {}), '(sparseMatrix)\n', (11954, 11968), False, 'from numpy import count_nonzero\n'), ((3646, 3653), 'numpy.linalg.norm', 'norm', (['a'], {}), '(a)\n', (3650, 3653), False, 'from numpy.linalg import norm\n'), ((3654, 3661), 'numpy.linalg.norm', 'norm', (['b'], {}), '(b)\n', (3658, 3661), False, 'from numpy.linalg import norm\n'), ((9100, 9132), 'numpy.random.randint', 'np.random.randint', ([], {'low': '(3)', 'high': '(5)'}), '(low=3, high=5)\n', (9117, 9132), True, 'import numpy as np\n'), ((9168, 9193), 'numpy.random.randint', 'np.random.randint', (['(10)', '(50)'], {}), '(10, 50)\n', (9185, 9193), True, 'import numpy as np\n'), ((12180, 12218), 'scipy.sparse.csr_matrix.sum', 'scipy.sparse.csr_matrix.sum', (['P'], {'axis': '(1)'}), '(P, axis=1)\n', (12207, 12218), False, 'import scipy\n'), ((12316, 12354), 'scipy.sparse.csr_matrix.sum', 'scipy.sparse.csr_matrix.sum', (['Q'], {'axis': '(0)'}), '(Q, axis=0)\n', (12343, 12354), False, 'import scipy\n'), ((9672, 9701), 'numpy.random.binomial', 'np.random.binomial', (['(1)', '(0.7)', '(1)'], {}), '(1, 0.7, 1)\n', (9690, 9701), True, 'import numpy as np\n'), ((10122, 10151), 'numpy.random.binomial', 'np.random.binomial', (['(1)', '(0.1)', '(1)'], {}), '(1, 0.1, 1)\n', (10140, 10151), True, 'import numpy as np\n'), ((9784, 9910), 'numpy.random.randint', 'np.random.randint', (["(data[data['_id'] == id_temp]['Max_Time'] / 4)", "data[data['_id'] == self.articles_served[m]]['Max_Time']"], {}), "(data[data['_id'] == id_temp]['Max_Time'] / 4, data[data[\n '_id'] == self.articles_served[m]]['Max_Time'])\n", (9801, 9910), True, 'import numpy as np\n'), ((10234, 10296), 'numpy.random.randint', 'np.random.randint', (['(0)', "data[data['_id'] == id_temp]['Max_Time']"], {}), "(0, data[data['_id'] == id_temp]['Max_Time'])\n", (10251, 10296), True, 'import numpy as np\n')]
import json from pathlib import Path import numpy as np from deepcave.runs import Status from deepcave.runs.converters.deepcave import DeepCAVERun from deepcave.runs.objective import Objective from deepcave.runs.run import Run from deepcave.utils.hash import file_to_hash class SMACRun(Run): prefix = "SMAC" _initial_order = 2 @property def hash(self) -> str: """ The id from the files in the current working_dir/run_name/*. For example, history.json could be read and hashed. Idea behind: If id changed, then we have to update cached trials. """ # Use hash of history.json as id return file_to_hash(self.path / "runhistory.json") @classmethod def from_path(cls, path: Path) -> "SMACRun": """ Based on working_dir/run_name/*, return a new trials object. """ # For SMAC, we create a new run object # Read configspace from ConfigSpace.read_and_write import json as cs_json with (path / "configspace.json").open("r") as f: configspace = cs_json.read(f.read()) # Read objectives # We have to define it ourselves, because we don't know the type of the objective # Only lock lower objective = Objective("Cost", lower=0) # Read meta # Everything else is ignored mapping = { "deterministic": "deterministic", "run_obj": "Run Objective", "cutoff": "Algorithm Time Limit", "memory_limit": "Memory Limit", "wallclock_limit": "Wallclock Limit", "initial_incumbent": "Initial Incumbent", } meta = {} with (path / "scenario.txt").open() as f: for line in f.readlines(): items = line.split(" = ") arg = items[0] value = items[1] # Remove \n value = value.replace("\n", "") if arg in mapping: meta[mapping[arg]] = value run = SMACRun( path.stem, configspace=configspace, objectives=objective, meta=meta ) # TODO: Make it better run._path = path # Iterate over the runhistory with (path / "runhistory.json").open() as json_file: all_data = json.load(json_file) data = all_data["data"] config_origins = all_data["config_origins"] configs = all_data["configs"] first_starttime = None seeds = [] for (config_id, instance_id, seed, budget), ( cost, time, status, starttime, endtime, additional_info, ) in data: config_id = str(config_id) config = configs[config_id] if seed not in seeds: seeds.append(seed) if len(seeds) > 1: raise RuntimeError("Multiple seeds are not supported.") if instance_id is not None: raise RuntimeError("Instances are not supported.") if first_starttime is None: first_starttime = starttime starttime = starttime - first_starttime endtime = endtime - first_starttime status = status["__enum__"] if "SUCCESS" in status: status = Status.SUCCESS elif "TIMEOUT" in status: status = Status.TIMEOUT elif "ABORT" in status: status = Status.ABORTED elif "MEMOUT" in status: status = Status.MEMORYOUT elif "RUNNING" in status: status = Status.RUNNING else: status = Status.CRASHED if status != Status.SUCCESS: # We don't want cost included which are failed cost = None # Round budget budget = np.round(budget, 2) run.add( costs=[cost], # Having only single objective here config=config, budget=budget, start_time=starttime, end_time=endtime, status=status, origin=config_origins[config_id], additional=additional_info, ) return run
[ "deepcave.utils.hash.file_to_hash", "deepcave.runs.objective.Objective", "numpy.round", "json.load" ]
[((657, 700), 'deepcave.utils.hash.file_to_hash', 'file_to_hash', (["(self.path / 'runhistory.json')"], {}), "(self.path / 'runhistory.json')\n", (669, 700), False, 'from deepcave.utils.hash import file_to_hash\n'), ((1270, 1296), 'deepcave.runs.objective.Objective', 'Objective', (['"""Cost"""'], {'lower': '(0)'}), "('Cost', lower=0)\n", (1279, 1296), False, 'from deepcave.runs.objective import Objective\n'), ((2333, 2353), 'json.load', 'json.load', (['json_file'], {}), '(json_file)\n', (2342, 2353), False, 'import json\n'), ((3958, 3977), 'numpy.round', 'np.round', (['budget', '(2)'], {}), '(budget, 2)\n', (3966, 3977), True, 'import numpy as np\n')]
"""Single element 2-, 3-, and 2+3-body kernels. The kernel functions to choose: * Two body: * two_body: force kernel * two_body_en: energy kernel * two_body_grad: gradient of kernel function * two_body_force_en: energy force kernel * Three body: * three_body, * three_body_grad, * three_body_en, * three_body_force_en, * Two plus three body: * two_plus_three_body, * two_plus_three_body_grad, * two_plus_three_en, * two_plus_three_force_en * Two plus three plus many body: * two_plus_three_plus_many_body, * two_plus_three_plus_many_body_grad, * two_plus_three_plus_many_body_en, * two_plus_three_plus_many_body_force_en **Example:** >>> gp_model = GaussianProcess(kernel_name='2b', <other arguments>) """ import numpy as np from math import exp from flare.env import AtomicEnvironment import flare.cutoffs as cf from numba import njit from flare.kernels.kernels import force_helper, grad_constants, grad_helper, \ force_energy_helper, three_body_en_helper, three_body_helper_1, \ three_body_helper_2, three_body_grad_helper_1, three_body_grad_helper_2 # ----------------------------------------------------------------------------- # two plus three body kernels # ----------------------------------------------------------------------------- def two_plus_three_body(env1: AtomicEnvironment, env2: AtomicEnvironment, d1: int, d2: int, hyps, cutoffs, cutoff_func=cf.quadratic_cutoff): """2+3-body single-element kernel between two force components. Args: env1 (AtomicEnvironment): First local environment. env2 (AtomicEnvironment): Second local environment. d1 (int): Force component of the first environment. d2 (int): Force component of the second environment. hyps (np.ndarray): Hyperparameters of the kernel function (sig1, ls1, sig2, ls2, sig_n). cutoffs (np.ndarray): Two-element array containing the 2- and 3-body cutoffs. cutoff_func (Callable): Cutoff function of the kernel. Return: float: Value of the 2+3-body kernel. """ two_term = two_body_jit(env1.bond_array_2, env2.bond_array_2, d1, d2, hyps[0], hyps[1], cutoffs[0], cutoff_func) three_term = \ three_body_jit(env1.bond_array_3, env2.bond_array_3, env1.cross_bond_inds, env2.cross_bond_inds, env1.cross_bond_dists, env2.cross_bond_dists, env1.triplet_counts, env2.triplet_counts, d1, d2, hyps[2], hyps[3], cutoffs[1], cutoff_func) return two_term + three_term def two_plus_three_body_grad(env1, env2, d1, d2, hyps, cutoffs, cutoff_func=cf.quadratic_cutoff): """2+3-body single-element kernel between two force components and its gradient with respect to the hyperparameters. Args: env1 (AtomicEnvironment): First local environment. env2 (AtomicEnvironment): Second local environment. d1 (int): Force component of the first environment. d2 (int): Force component of the second environment. hyps (np.ndarray): Hyperparameters of the kernel function (sig1, ls1, sig2, ls2, sig_n). cutoffs (np.ndarray): Two-element array containing the 2- and 3-body cutoffs. cutoff_func (Callable): Cutoff function of the kernel. Return: (float, np.ndarray): Value of the 2+3-body kernel and its gradient with respect to the hyperparameters. """ kern2, ls2, sig2 = \ two_body_grad_jit(env1.bond_array_2, env2.bond_array_2, d1, d2, hyps[0], hyps[1], cutoffs[0], cutoff_func) kern3, sig3, ls3 = \ three_body_grad_jit(env1.bond_array_3, env2.bond_array_3, env1.cross_bond_inds, env2.cross_bond_inds, env1.cross_bond_dists, env2.cross_bond_dists, env1.triplet_counts, env2.triplet_counts, d1, d2, hyps[2], hyps[3], cutoffs[1], cutoff_func) return kern2 + kern3, np.array([sig2, ls2, sig3, ls3]) def two_plus_three_force_en(env1, env2, d1, hyps, cutoffs, cutoff_func=cf.quadratic_cutoff): """2+3-body single-element kernel between a force component and a local energy. Args: env1 (AtomicEnvironment): Local environment associated with the force component. env2 (AtomicEnvironment): Local environment associated with the local energy. d1 (int): Force component of the first environment. hyps (np.ndarray): Hyperparameters of the kernel function (sig1, ls1, sig2, ls2). cutoffs (np.ndarray): Two-element array containing the 2- and 3-body cutoffs. cutoff_func (Callable): Cutoff function of the kernel. Return: float: Value of the 2+3-body force/energy kernel. """ two_term = two_body_force_en_jit(env1.bond_array_2, env2.bond_array_2, d1, hyps[0], hyps[1], cutoffs[0], cutoff_func) / 2 three_term = \ three_body_force_en_jit(env1.bond_array_3, env2.bond_array_3, env1.cross_bond_inds, env2.cross_bond_inds, env1.cross_bond_dists, env2.cross_bond_dists, env1.triplet_counts, env2.triplet_counts, d1, hyps[2], hyps[3], cutoffs[1], cutoff_func) / 3 return two_term + three_term def two_plus_three_en(env1, env2, hyps, cutoffs, cutoff_func=cf.quadratic_cutoff): """2+3-body single-element kernel between two local energies. Args: env1 (AtomicEnvironment): First local environment. env2 (AtomicEnvironment): Second local environment. hyps (np.ndarray): Hyperparameters of the kernel function (sig1, ls1, sig2, ls2). cutoffs (np.ndarray): Two-element array containing the 2- and 3-body cutoffs. cutoff_func (Callable): Cutoff function of the kernel. Return: float: Value of the 2+3-body force/energy kernel. """ two_term = two_body_en_jit(env1.bond_array_2, env2.bond_array_2, hyps[0], hyps[1], cutoffs[0], cutoff_func) three_term = \ three_body_en_jit(env1.bond_array_3, env2.bond_array_3, env1.cross_bond_inds, env2.cross_bond_inds, env1.cross_bond_dists, env2.cross_bond_dists, env1.triplet_counts, env2.triplet_counts, hyps[2], hyps[3], cutoffs[1], cutoff_func) return two_term + three_term # ----------------------------------------------------------------------------- # two plus three plus many body kernels # ----------------------------------------------------------------------------- def two_plus_three_plus_many_body(env1: AtomicEnvironment, env2: AtomicEnvironment, d1: int, d2: int, hyps, cutoffs, cutoff_func=cf.quadratic_cutoff): """2+3-body single-element kernel between two force components. Args: env1 (AtomicEnvironment): First local environment. env2 (AtomicEnvironment): Second local environment. d1 (int): Force component of the first environment. d2 (int): Force component of the second environment. hyps (np.ndarray): Hyperparameters of the kernel function (sig2, ls2, sig3, ls3, sigm, lsm, sig_n). cutoffs (np.ndarray): Two-element array containing the 2- and 3-body cutoffs. cutoff_func (Callable): Cutoff function of the kernel. Return: float: Value of the 2+3+many-body kernel. """ two_term = two_body_jit(env1.bond_array_2, env2.bond_array_2, d1, d2, hyps[0], hyps[1], cutoffs[0], cutoff_func) three_term = \ three_body_jit(env1.bond_array_3, env2.bond_array_3, env1.cross_bond_inds, env2.cross_bond_inds, env1.cross_bond_dists, env2.cross_bond_dists, env1.triplet_counts, env2.triplet_counts, d1, d2, hyps[2], hyps[3], cutoffs[1], cutoff_func) many_term = many_body_jit(env1.bond_array_mb, env2.bond_array_mb, env1.neigh_dists_mb, env2.neigh_dists_mb, env1.num_neighs_mb, env2.num_neighs_mb, d1, d2, hyps[4], hyps[5], cutoffs[2], cutoff_func) return two_term + three_term + many_term def two_plus_three_plus_many_body_grad(env1: AtomicEnvironment, env2: AtomicEnvironment, d1: int, d2: int, hyps, cutoffs, cutoff_func=cf.quadratic_cutoff): """2+3+many-body single-element kernel between two force components. Args: env1 (AtomicEnvironment): First local environment. env2 (AtomicEnvironment): Second local environment. d1 (int): Force component of the first environment. d2 (int): Force component of the second environment. hyps (np.ndarray): Hyperparameters of the kernel function (sig2, ls2, sig3, ls3, sigm, lsm, sig_n). cutoffs (np.ndarray): Two-element array containing the 2- and 3-body cutoffs. cutoff_func (Callable): Cutoff function of the kernel. Return: float: Value of the 2+3+many-body kernel. """ kern2, ls2, sig2 = \ two_body_grad_jit(env1.bond_array_2, env2.bond_array_2, d1, d2, hyps[0], hyps[1], cutoffs[0], cutoff_func) kern3, sig3, ls3 = \ three_body_grad_jit(env1.bond_array_3, env2.bond_array_3, env1.cross_bond_inds, env2.cross_bond_inds, env1.cross_bond_dists, env2.cross_bond_dists, env1.triplet_counts, env2.triplet_counts, d1, d2, hyps[2], hyps[3], cutoffs[1], cutoff_func) kern_many, sigm, lsm = many_body_grad_jit(env1.bond_array_mb, env2.bond_array_mb, env1.neigh_dists_mb, env2.neigh_dists_mb, env1.num_neighs_mb, env2.num_neighs_mb, d1, d2, hyps[4], hyps[5], cutoffs[2], cutoff_func) return kern2 + kern3 + kern_many, np.array([sig2, ls2, sig3, ls3, sigm, lsm]) def two_plus_three_plus_many_body_force_en(env1: AtomicEnvironment, env2: AtomicEnvironment, d1: int, hyps, cutoffs, cutoff_func=cf.quadratic_cutoff): """2+3+many-body single-element kernel between two force and energy components. Args: env1 (AtomicEnvironment): First local environment. env2 (AtomicEnvironment): Second local environment. d1 (int): Force component of the first environment. hyps (np.ndarray): Hyperparameters of the kernel function (sig2, ls2, sig3, ls3, sigm, lsm, sig_n). cutoffs (np.ndarray): Two-element array containing the 2- and 3-body cutoffs. cutoff_func (Callable): Cutoff function of the kernel. Return: float: Value of the 2+3+many-body kernel. """ two_term = two_body_force_en_jit(env1.bond_array_2, env2.bond_array_2, d1, hyps[0], hyps[1], cutoffs[0], cutoff_func) / 2 three_term = \ three_body_force_en_jit(env1.bond_array_3, env2.bond_array_3, env1.cross_bond_inds, env2.cross_bond_inds, env1.cross_bond_dists, env2.cross_bond_dists, env1.triplet_counts, env2.triplet_counts, d1, hyps[2], hyps[3], cutoffs[1], cutoff_func) / 3 many_term = many_body_force_en_jit(env1.bond_array_mb, env2.bond_array_mb, env1.neigh_dists_mb, env1.num_neighs_mb, d1, hyps[4], hyps[5], cutoffs[2], cutoff_func) return two_term + three_term + many_term def two_plus_three_plus_many_body_en(env1: AtomicEnvironment, env2: AtomicEnvironment, hyps, cutoffs, cutoff_func=cf.quadratic_cutoff): """2+3+many-body single-element energy kernel. Args: env1 (AtomicEnvironment): First local environment. env2 (AtomicEnvironment): Second local environment. hyps (np.ndarray): Hyperparameters of the kernel function (sig2, ls2, sig3, ls3, sigm, lsm, sig_n). cutoffs (np.ndarray): Two-element array containing the 2- and 3-body cutoffs. cutoff_func (Callable): Cutoff function of the kernel. Return: float: Value of the 2+3+many-body kernel. """ two_term = two_body_en_jit(env1.bond_array_2, env2.bond_array_2, hyps[0], hyps[1], cutoffs[0], cutoff_func) three_term = \ three_body_en_jit(env1.bond_array_3, env2.bond_array_3, env1.cross_bond_inds, env2.cross_bond_inds, env1.cross_bond_dists, env2.cross_bond_dists, env1.triplet_counts, env2.triplet_counts, hyps[2], hyps[3], cutoffs[1], cutoff_func) many_term = many_body_en_jit(env1.bond_array_mb, env2.bond_array_mb, hyps[4], hyps[5], cutoffs[2], cutoff_func) return two_term + three_term + many_term # ----------------------------------------------------------------------------- # two body kernels # ----------------------------------------------------------------------------- def two_body(env1, env2, d1, d2, hyps, cutoffs, cutoff_func=cf.quadratic_cutoff): """2-body single-element kernel between two force components. Args: env1 (AtomicEnvironment): First local environment. env2 (AtomicEnvironment): Second local environment. d1 (int): Force component of the first environment. d2 (int): Force component of the second environment. hyps (np.ndarray): Hyperparameters of the kernel function (sig, ls). cutoffs (np.ndarray): One-element array containing the 2-body cutoff. cutoff_func (Callable): Cutoff function of the kernel. Return: float: Value of the 2-body kernel. """ sig = hyps[0] ls = hyps[1] r_cut = cutoffs[0] return two_body_jit(env1.bond_array_2, env2.bond_array_2, d1, d2, sig, ls, r_cut, cutoff_func) def two_body_grad(env1, env2, d1, d2, hyps, cutoffs, cutoff_func=cf.quadratic_cutoff): """2-body single-element kernel between two force components and its gradient with respect to the hyperparameters. Args: env1 (AtomicEnvironment): First local environment. env2 (AtomicEnvironment): Second local environment. d1 (int): Force component of the first environment. d2 (int): Force component of the second environment. hyps (np.ndarray): Hyperparameters of the kernel function (sig, ls). cutoffs (np.ndarray): One-element array containing the 2-body cutoff. cutoff_func (Callable): Cutoff function of the kernel. Return: (float, np.ndarray): Value of the 2-body kernel and its gradient with respect to the hyperparameters. """ sig = hyps[0] ls = hyps[1] r_cut = cutoffs[0] kernel, ls_derv, sig_derv = \ two_body_grad_jit(env1.bond_array_2, env2.bond_array_2, d1, d2, sig, ls, r_cut, cutoff_func) kernel_grad = np.array([sig_derv, ls_derv]) return kernel, kernel_grad def two_body_force_en(env1, env2, d1, hyps, cutoffs, cutoff_func=cf.quadratic_cutoff): """2-body single-element kernel between a force component and a local energy. Args: env1 (AtomicEnvironment): Local environment associated with the force component. env2 (AtomicEnvironment): Local environment associated with the local energy. d1 (int): Force component of the first environment. hyps (np.ndarray): Hyperparameters of the kernel function (sig, ls). cutoffs (np.ndarray): One-element array containing the 2-body cutoff. cutoff_func (Callable): Cutoff function of the kernel. Return: float: Value of the 2-body force/energy kernel. """ sig = hyps[0] ls = hyps[1] r_cut = cutoffs[0] # divide by two to account for double counting return two_body_force_en_jit(env1.bond_array_2, env2.bond_array_2, d1, sig, ls, r_cut, cutoff_func) / 2 def two_body_en(env1, env2, hyps, cutoffs, cutoff_func=cf.quadratic_cutoff): """2-body single-element kernel between two local energies. Args: env1 (AtomicEnvironment): First local environment. env2 (AtomicEnvironment): Second local environment. hyps (np.ndarray): Hyperparameters of the kernel function (sig, ls). cutoffs (np.ndarray): One-element array containing the 2-body cutoff. cutoff_func (Callable): Cutoff function of the kernel. Return: float: Value of the 2-body force/energy kernel. """ sig = hyps[0] ls = hyps[1] r_cut = cutoffs[0] return two_body_en_jit(env1.bond_array_2, env2.bond_array_2, sig, ls, r_cut, cutoff_func) # ----------------------------------------------------------------------------- # three body kernels # ----------------------------------------------------------------------------- def three_body(env1, env2, d1, d2, hyps, cutoffs, cutoff_func=cf.quadratic_cutoff): """3-body single-element kernel between two force components. Args: env1 (AtomicEnvironment): First local environment. env2 (AtomicEnvironment): Second local environment. d1 (int): Force component of the first environment. d2 (int): Force component of the second environment. hyps (np.ndarray): Hyperparameters of the kernel function (sig, ls). cutoffs (np.ndarray): Two-element array containing the 2- and 3-body cutoffs. cutoff_func (Callable): Cutoff function of the kernel. Return: float: Value of the 3-body kernel. """ sig = hyps[0] ls = hyps[1] r_cut = cutoffs[1] return three_body_jit(env1.bond_array_3, env2.bond_array_3, env1.cross_bond_inds, env2.cross_bond_inds, env1.cross_bond_dists, env2.cross_bond_dists, env1.triplet_counts, env2.triplet_counts, d1, d2, sig, ls, r_cut, cutoff_func) def three_body_grad(env1, env2, d1, d2, hyps, cutoffs, cutoff_func=cf.quadratic_cutoff): """3-body single-element kernel between two force components and its gradient with respect to the hyperparameters. Args: env1 (AtomicEnvironment): First local environment. env2 (AtomicEnvironment): Second local environment. d1 (int): Force component of the first environment. d2 (int): Force component of the second environment. hyps (np.ndarray): Hyperparameters of the kernel function (sig, ls). cutoffs (np.ndarray): Two-element array containing the 2- and 3-body cutoffs. cutoff_func (Callable): Cutoff function of the kernel. Return: (float, np.ndarray): Value of the 3-body kernel and its gradient with respect to the hyperparameters. """ sig = hyps[0] ls = hyps[1] r_cut = cutoffs[1] kernel, sig_derv, ls_derv = three_body_grad_jit(env1.bond_array_3, env2.bond_array_3, env1.cross_bond_inds, env2.cross_bond_inds, env1.cross_bond_dists, env2.cross_bond_dists, env1.triplet_counts, env2.triplet_counts, d1, d2, sig, ls, r_cut, cutoff_func) kernel_grad = np.array([sig_derv, ls_derv]) return kernel, kernel_grad def three_body_force_en(env1, env2, d1, hyps, cutoffs, cutoff_func=cf.quadratic_cutoff): """3-body single-element kernel between a force component and a local energy. Args: env1 (AtomicEnvironment): Local environment associated with the force component. env2 (AtomicEnvironment): Local environment associated with the local energy. d1 (int): Force component of the first environment. hyps (np.ndarray): Hyperparameters of the kernel function (sig, ls). cutoffs (np.ndarray): Two-element array containing the 2- and 3-body cutoffs. cutoff_func (Callable): Cutoff function of the kernel. Return: float: Value of the 3-body force/energy kernel. """ sig = hyps[0] ls = hyps[1] r_cut = cutoffs[1] # divide by three to account for triple counting return three_body_force_en_jit(env1.bond_array_3, env2.bond_array_3, env1.cross_bond_inds, env2.cross_bond_inds, env1.cross_bond_dists, env2.cross_bond_dists, env1.triplet_counts, env2.triplet_counts, d1, sig, ls, r_cut, cutoff_func) / 3 def three_body_en(env1, env2, hyps, cutoffs, cutoff_func=cf.quadratic_cutoff): """3-body single-element kernel between two local energies. Args: env1 (AtomicEnvironment): First local environment. env2 (AtomicEnvironment): Second local environment. hyps (np.ndarray): Hyperparameters of the kernel function (sig, ls). cutoffs (np.ndarray): Two-element array containing the 2- and 3-body cutoffs. cutoff_func (Callable): Cutoff function of the kernel. Return: float: Value of the 3-body force/energy kernel. """ sig = hyps[0] ls = hyps[1] r_cut = cutoffs[1] return three_body_en_jit(env1.bond_array_3, env2.bond_array_3, env1.cross_bond_inds, env2.cross_bond_inds, env1.cross_bond_dists, env2.cross_bond_dists, env1.triplet_counts, env2.triplet_counts, sig, ls, r_cut, cutoff_func) # ----------------------------------------------------------------------------- # many body kernels # ----------------------------------------------------------------------------- def many_body(env1, env2, d1, d2, hyps, cutoffs, cutoff_func=cf.quadratic_cutoff): """many-body single-element kernel between two forces. Args: env1 (AtomicEnvironment): First local environment. env2 (AtomicEnvironment): Second local environment. d1 (int): Force component of the first environment. d2 (int): Force component of the second environment. hyps (np.ndarray): Hyperparameters of the kernel function (sig, ls). cutoffs (np.ndarray): Two-element array containing the 2-, 3-, and many-body cutoffs. cutoff_func (Callable): Cutoff function of the kernel. Return: float: Value of the many-body force/force kernel. """ sig = hyps[0] ls = hyps[1] r_cut = cutoffs[2] bond_array_1 = env1.bond_array_mb bond_array_2 = env2.bond_array_mb neigh_dists_1 = env1.neigh_dists_mb num_neigh_1 = env1.num_neighs_mb neigh_dists_2 = env2.neigh_dists_mb num_neigh_2 = env2.num_neighs_mb return many_body_jit(bond_array_1, bond_array_2, neigh_dists_1, neigh_dists_2, num_neigh_1, num_neigh_2, d1, d2, sig, ls, r_cut, cutoff_func) def many_body_grad(env1, env2, d1, d2, hyps, cutoffs, cutoff_func=cf.quadratic_cutoff): """many-body single-element kernel between two force components and its gradient with respect to the hyperparameters. Args: env1 (AtomicEnvironment): First local environment. env2 (AtomicEnvironment): Second local environment. d1 (int): Force component of the first environment. d2 (int): Force component of the second environment. hyps (np.ndarray): Hyperparameters of the kernel function (sig, ls). cutoffs (np.ndarray): Two-element array containing the 2-, 3-, and many-body cutoffs. cutoff_func (Callable): Cutoff function of the kernel. Return: (float, np.ndarray): Value of the many-body kernel and its gradient with respect to the hyperparameters. """ sig = hyps[0] ls = hyps[1] r_cut = cutoffs[2] bond_array_1 = env1.bond_array_mb bond_array_2 = env2.bond_array_mb neigh_dists_1 = env1.neigh_dists_mb num_neigh_1 = env1.num_neighs_mb neigh_dists_2 = env2.neigh_dists_mb num_neigh_2 = env2.num_neighs_mb kernel, sig_derv, ls_derv = many_body_grad_jit(bond_array_1, bond_array_2, neigh_dists_1, neigh_dists_2, num_neigh_1, num_neigh_2, d1, d2, sig, ls, r_cut, cutoff_func) kernel_grad = np.array([sig_derv, ls_derv]) return kernel, kernel_grad def many_body_force_en(env1, env2, d1, hyps, cutoffs, cutoff_func=cf.quadratic_cutoff): """many-body single-element kernel between two local energies. Args: env1 (AtomicEnvironment): First local environment. env2 (AtomicEnvironment): Second local environment. hyps (np.ndarray): Hyperparameters of the kernel function (sig, ls). cutoffs (np.ndarray): Two-element array containing the 2-, 3-, and many-body cutoffs. cutoff_func (Callable): Cutoff function of the kernel. Return: float: Value of the many-body force/energy kernel. """ sig = hyps[0] ls = hyps[1] r_cut = cutoffs[2] # divide by three to account for triple counting return many_body_force_en_jit(env1.bond_array_mb, env2.bond_array_mb, env1.neigh_dists_mb, env2.num_neighs_mb, d1, sig, ls, r_cut, cutoff_func) def many_body_en(env1, env2, hyps, cutoffs, cutoff_func=cf.quadratic_cutoff): """many-body single-element kernel between two local energies. Args: env1 (AtomicEnvironment): First local environment. env2 (AtomicEnvironment): Second local environment. hyps (np.ndarray): Hyperparameters of the kernel function (sig, ls). cutoffs (np.ndarray): Two-element array containing the 2-, 3-, and many-body cutoffs. cutoff_func (Callable): Cutoff function of the kernel. Return: float: Value of the many-body energy/energy kernel. """ sig = hyps[0] ls = hyps[1] r_cut = cutoffs[2] bond_array_1 = env1.bond_array_mb bond_array_2 = env2.bond_array_mb return many_body_en_jit(bond_array_1, bond_array_2, sig, ls, r_cut, cutoff_func) # ----------------------------------------------------------------------------- # two body numba functions # ----------------------------------------------------------------------------- @njit def two_body_jit(bond_array_1, bond_array_2, d1, d2, sig, ls, r_cut, cutoff_func): """2-body single-element kernel between two force components accelerated with Numba. Args: bond_array_1 (np.ndarray): 2-body bond array of the first local environment. bond_array_2 (np.ndarray): 2-body bond array of the second local environment. d1 (int): Force component of the first environment (1=x, 2=y, 3=z). d2 (int): Force component of the second environment (1=x, 2=y, 3=z). sig (float): 2-body signal variance hyperparameter. ls (float): 2-body length scale hyperparameter. r_cut (float): 2-body cutoff radius. cutoff_func (Callable): Cutoff function. Return: float: Value of the 2-body kernel. """ kern = 0 ls1 = 1 / (2 * ls * ls) ls2 = 1 / (ls * ls) ls3 = ls2 * ls2 sig2 = sig * sig for m in range(bond_array_1.shape[0]): ri = bond_array_1[m, 0] ci = bond_array_1[m, d1] fi, fdi = cutoff_func(r_cut, ri, ci) for n in range(bond_array_2.shape[0]): rj = bond_array_2[n, 0] cj = bond_array_2[n, d2] fj, fdj = cutoff_func(r_cut, rj, cj) r11 = ri - rj A = ci * cj B = r11 * ci C = r11 * cj D = r11 * r11 kern += force_helper(A, B, C, D, fi, fj, fdi, fdj, ls1, ls2, ls3, sig2) return kern @njit def two_body_grad_jit(bond_array_1, bond_array_2, d1, d2, sig, ls, r_cut, cutoff_func): """2-body single-element kernel between two force components and its gradient with respect to the hyperparameters. Args: bond_array_1 (np.ndarray): 2-body bond array of the first local environment. bond_array_2 (np.ndarray): 2-body bond array of the second local environment. d1 (int): Force component of the first environment (1=x, 2=y, 3=z). d2 (int): Force component of the second environment (1=x, 2=y, 3=z). sig (float): 2-body signal variance hyperparameter. ls (float): 2-body length scale hyperparameter. r_cut (float): 2-body cutoff radius. cutoff_func (Callable): Cutoff function. Returns: (float, float): Value of the 2-body kernel and its gradient with respect to the hyperparameters. """ kern = 0 sig_derv = 0 ls_derv = 0 sig2, sig3, ls1, ls2, ls3, ls4, ls5, ls6 = grad_constants(sig, ls) for m in range(bond_array_1.shape[0]): ri = bond_array_1[m, 0] ci = bond_array_1[m, d1] fi, fdi = cutoff_func(r_cut, ri, ci) for n in range(bond_array_2.shape[0]): rj = bond_array_2[n, 0] cj = bond_array_2[n, d2] fj, fdj = cutoff_func(r_cut, rj, cj) r11 = ri - rj A = ci * cj B = r11 * ci C = r11 * cj D = r11 * r11 kern_term, sig_term, ls_term = \ grad_helper(A, B, C, D, fi, fj, fdi, fdj, ls1, ls2, ls3, ls4, ls5, ls6, sig2, sig3) kern += kern_term sig_derv += sig_term ls_derv += ls_term return kern, ls_derv, sig_derv @njit def two_body_force_en_jit(bond_array_1, bond_array_2, d1, sig, ls, r_cut, cutoff_func): """2-body single-element kernel between a force component and a local energy accelerated with Numba. Args: bond_array_1 (np.ndarray): 2-body bond array of the first local environment. bond_array_2 (np.ndarray): 2-body bond array of the second local environment. d1 (int): Force component of the first environment (1=x, 2=y, 3=z). sig (float): 2-body signal variance hyperparameter. ls (float): 2-body length scale hyperparameter. r_cut (float): 2-body cutoff radius. cutoff_func (Callable): Cutoff function. Returns: float: Value of the 2-body force/energy kernel. """ kern = 0 ls1 = 1 / (2 * ls * ls) ls2 = 1 / (ls * ls) sig2 = sig * sig for m in range(bond_array_1.shape[0]): ri = bond_array_1[m, 0] ci = bond_array_1[m, d1] fi, fdi = cutoff_func(r_cut, ri, ci) for n in range(bond_array_2.shape[0]): rj = bond_array_2[n, 0] fj, _ = cutoff_func(r_cut, rj, 0) r11 = ri - rj B = r11 * ci D = r11 * r11 kern += force_energy_helper(B, D, fi, fj, fdi, ls1, ls2, sig2) return kern @njit def two_body_en_jit(bond_array_1, bond_array_2, sig, ls, r_cut, cutoff_func): """2-body single-element kernel between two local energies accelerated with Numba. Args: bond_array_1 (np.ndarray): 2-body bond array of the first local environment. bond_array_2 (np.ndarray): 2-body bond array of the second local environment. sig (float): 2-body signal variance hyperparameter. ls (float): 2-body length scale hyperparameter. r_cut (float): 2-body cutoff radius. cutoff_func (Callable): Cutoff function. Returns: float: Value of the 2-body local energy kernel. """ kern = 0 ls1 = 1 / (2 * ls * ls) sig2 = sig * sig for m in range(bond_array_1.shape[0]): ri = bond_array_1[m, 0] fi, _ = cutoff_func(r_cut, ri, 0) for n in range(bond_array_2.shape[0]): rj = bond_array_2[n, 0] fj, _ = cutoff_func(r_cut, rj, 0) r11 = ri - rj kern += fi * fj * sig2 * exp(-r11 * r11 * ls1) return kern # ----------------------------------------------------------------------------- # three body numba functions # ----------------------------------------------------------------------------- @njit def three_body_jit(bond_array_1, bond_array_2, cross_bond_inds_1, cross_bond_inds_2, cross_bond_dists_1, cross_bond_dists_2, triplets_1, triplets_2, d1, d2, sig, ls, r_cut, cutoff_func): """3-body single-element kernel between two force components accelerated with Numba. Args: bond_array_1 (np.ndarray): 3-body bond array of the first local environment. bond_array_2 (np.ndarray): 3-body bond array of the second local environment. cross_bond_inds_1 (np.ndarray): Two dimensional array whose row m contains the indices of atoms n > m in the first local environment that are within a distance r_cut of both atom n and the central atom. cross_bond_inds_2 (np.ndarray): Two dimensional array whose row m contains the indices of atoms n > m in the second local environment that are within a distance r_cut of both atom n and the central atom. cross_bond_dists_1 (np.ndarray): Two dimensional array whose row m contains the distances from atom m of atoms n > m in the first local environment that are within a distance r_cut of both atom n and the central atom. cross_bond_dists_2 (np.ndarray): Two dimensional array whose row m contains the distances from atom m of atoms n > m in the second local environment that are within a distance r_cut of both atom n and the central atom. triplets_1 (np.ndarray): One dimensional array of integers whose entry m is the number of atoms in the first local environment that are within a distance r_cut of atom m. triplets_2 (np.ndarray): One dimensional array of integers whose entry m is the number of atoms in the second local environment that are within a distance r_cut of atom m. d1 (int): Force component of the first environment. d2 (int): Force component of the second environment. sig (float): 3-body signal variance hyperparameter. ls (float): 3-body length scale hyperparameter. r_cut (float): 3-body cutoff radius. cutoff_func (Callable): Cutoff function. Return: float: Value of the 3-body kernel. """ kern = 0 # pre-compute constants that appear in the inner loop sig2 = sig * sig ls1 = 1 / (2 * ls * ls) ls2 = 1 / (ls * ls) ls3 = ls2 * ls2 for m in range(bond_array_1.shape[0]): ri1 = bond_array_1[m, 0] ci1 = bond_array_1[m, d1] fi1, fdi1 = cutoff_func(r_cut, ri1, ci1) for n in range(triplets_1[m]): ind1 = cross_bond_inds_1[m, m + n + 1] ri2 = bond_array_1[ind1, 0] ci2 = bond_array_1[ind1, d1] fi2, fdi2 = cutoff_func(r_cut, ri2, ci2) ri3 = cross_bond_dists_1[m, m + n + 1] fi3, _ = cutoff_func(r_cut, ri3, 0) fi = fi1 * fi2 * fi3 fdi = fdi1 * fi2 * fi3 + fi1 * fdi2 * fi3 for p in range(bond_array_2.shape[0]): rj1 = bond_array_2[p, 0] cj1 = bond_array_2[p, d2] fj1, fdj1 = cutoff_func(r_cut, rj1, cj1) for q in range(triplets_2[p]): ind2 = cross_bond_inds_2[p, p + 1 + q] rj2 = bond_array_2[ind2, 0] cj2 = bond_array_2[ind2, d2] fj2, fdj2 = cutoff_func(r_cut, rj2, cj2) rj3 = cross_bond_dists_2[p, p + 1 + q] fj3, _ = cutoff_func(r_cut, rj3, 0) fj = fj1 * fj2 * fj3 fdj = fdj1 * fj2 * fj3 + fj1 * fdj2 * fj3 kern += triplet_kernel(ci1, ci2, cj1, cj2, ri1, ri2, ri3, rj1, rj2, rj3, fi, fj, fdi, fdj, ls1, ls2, ls3, sig2) return kern @njit def three_body_grad_jit(bond_array_1, bond_array_2, cross_bond_inds_1, cross_bond_inds_2, cross_bond_dists_1, cross_bond_dists_2, triplets_1, triplets_2, d1, d2, sig, ls, r_cut, cutoff_func): """3-body single-element kernel between two force components and its gradient with respect to the hyperparameters. Args: bond_array_1 (np.ndarray): 3-body bond array of the first local environment. bond_array_2 (np.ndarray): 3-body bond array of the second local environment. cross_bond_inds_1 (np.ndarray): Two dimensional array whose row m contains the indices of atoms n > m in the first local environment that are within a distance r_cut of both atom n and the central atom. cross_bond_inds_2 (np.ndarray): Two dimensional array whose row m contains the indices of atoms n > m in the second local environment that are within a distance r_cut of both atom n and the central atom. cross_bond_dists_1 (np.ndarray): Two dimensional array whose row m contains the distances from atom m of atoms n > m in the first local environment that are within a distance r_cut of both atom n and the central atom. cross_bond_dists_2 (np.ndarray): Two dimensional array whose row m contains the distances from atom m of atoms n > m in the second local environment that are within a distance r_cut of both atom n and the central atom. triplets_1 (np.ndarray): One dimensional array of integers whose entry m is the number of atoms in the first local environment that are within a distance r_cut of atom m. triplets_2 (np.ndarray): One dimensional array of integers whose entry m is the number of atoms in the second local environment that are within a distance r_cut of atom m. d1 (int): Force component of the first environment. d2 (int): Force component of the second environment. sig (float): 3-body signal variance hyperparameter. ls (float): 3-body length scale hyperparameter. r_cut (float): 3-body cutoff radius. cutoff_func (Callable): Cutoff function. Returns: (float, float): Value of the 3-body kernel and its gradient with respect to the hyperparameters. """ kern = 0 sig_derv = 0 ls_derv = 0 # pre-compute constants that appear in the inner loop sig2, sig3, ls1, ls2, ls3, ls4, ls5, ls6 = grad_constants(sig, ls) for m in range(bond_array_1.shape[0]): ri1 = bond_array_1[m, 0] ci1 = bond_array_1[m, d1] fi1, fdi1 = cutoff_func(r_cut, ri1, ci1) for n in range(triplets_1[m]): ind1 = cross_bond_inds_1[m, m + n + 1] ri3 = cross_bond_dists_1[m, m + n + 1] ri2 = bond_array_1[ind1, 0] ci2 = bond_array_1[ind1, d1] fi2, fdi2 = cutoff_func(r_cut, ri2, ci2) fi3, _ = cutoff_func(r_cut, ri3, 0) fi = fi1 * fi2 * fi3 fdi = fdi1 * fi2 * fi3 + fi1 * fdi2 * fi3 for p in range(bond_array_2.shape[0]): rj1 = bond_array_2[p, 0] cj1 = bond_array_2[p, d2] fj1, fdj1 = cutoff_func(r_cut, rj1, cj1) for q in range(triplets_2[p]): ind2 = cross_bond_inds_2[p, p + q + 1] rj3 = cross_bond_dists_2[p, p + q + 1] rj2 = bond_array_2[ind2, 0] cj2 = bond_array_2[ind2, d2] fj2, fdj2 = cutoff_func(r_cut, rj2, cj2) fj3, _ = cutoff_func(r_cut, rj3, 0) fj = fj1 * fj2 * fj3 fdj = fdj1 * fj2 * fj3 + fj1 * fdj2 * fj3 N, O, X = \ triplet_kernel_grad(ci1, ci2, cj1, cj2, ri1, ri2, ri3, rj1, rj2, rj3, fi, fj, fdi, fdj, ls1, ls2, ls3, ls4, ls5, ls6, sig2, sig3) kern += N sig_derv += O ls_derv += X return kern, sig_derv, ls_derv @njit def three_body_force_en_jit(bond_array_1, bond_array_2, cross_bond_inds_1, cross_bond_inds_2, cross_bond_dists_1, cross_bond_dists_2, triplets_1, triplets_2, d1, sig, ls, r_cut, cutoff_func): """3-body single-element kernel between a force component and a local energy accelerated with Numba. Args: bond_array_1 (np.ndarray): 3-body bond array of the first local environment. bond_array_2 (np.ndarray): 3-body bond array of the second local environment. cross_bond_inds_1 (np.ndarray): Two dimensional array whose row m contains the indices of atoms n > m in the first local environment that are within a distance r_cut of both atom n and the central atom. cross_bond_inds_2 (np.ndarray): Two dimensional array whose row m contains the indices of atoms n > m in the second local environment that are within a distance r_cut of both atom n and the central atom. cross_bond_dists_1 (np.ndarray): Two dimensional array whose row m contains the distances from atom m of atoms n > m in the first local environment that are within a distance r_cut of both atom n and the central atom. cross_bond_dists_2 (np.ndarray): Two dimensional array whose row m contains the distances from atom m of atoms n > m in the second local environment that are within a distance r_cut of both atom n and the central atom. triplets_1 (np.ndarray): One dimensional array of integers whose entry m is the number of atoms in the first local environment that are within a distance r_cut of atom m. triplets_2 (np.ndarray): One dimensional array of integers whose entry m is the number of atoms in the second local environment that are within a distance r_cut of atom m. d1 (int): Force component of the first environment (1=x, 2=y, 3=z). sig (float): 3-body signal variance hyperparameter. ls (float): 3-body length scale hyperparameter. r_cut (float): 3-body cutoff radius. cutoff_func (Callable): Cutoff function. Returns: float: Value of the 3-body force/energy kernel. """ kern = 0 # pre-compute constants that appear in the inner loop sig2 = sig * sig ls1 = 1 / (2 * ls * ls) ls2 = 1 / (ls * ls) for m in range(bond_array_1.shape[0]): ri1 = bond_array_1[m, 0] ci1 = bond_array_1[m, d1] fi1, fdi1 = cutoff_func(r_cut, ri1, ci1) for n in range(triplets_1[m]): ind1 = cross_bond_inds_1[m, m + n + 1] ri2 = bond_array_1[ind1, 0] ci2 = bond_array_1[ind1, d1] fi2, fdi2 = cutoff_func(r_cut, ri2, ci2) ri3 = cross_bond_dists_1[m, m + n + 1] fi3, _ = cutoff_func(r_cut, ri3, 0) fi = fi1 * fi2 * fi3 fdi = fdi1 * fi2 * fi3 + fi1 * fdi2 * fi3 for p in range(bond_array_2.shape[0]): rj1 = bond_array_2[p, 0] fj1, _ = cutoff_func(r_cut, rj1, 0) for q in range(triplets_2[p]): ind2 = cross_bond_inds_2[p, p + q + 1] rj2 = bond_array_2[ind2, 0] fj2, _ = cutoff_func(r_cut, rj2, 0) rj3 = cross_bond_dists_2[p, p + q + 1] fj3, _ = cutoff_func(r_cut, rj3, 0) fj = fj1 * fj2 * fj3 kern += triplet_force_en_kernel(ci1, ci2, ri1, ri2, ri3, rj1, rj2, rj3, fi, fj, fdi, ls1, ls2, sig2) return kern @njit def three_body_en_jit(bond_array_1, bond_array_2, cross_bond_inds_1, cross_bond_inds_2, cross_bond_dists_1, cross_bond_dists_2, triplets_1, triplets_2, sig, ls, r_cut, cutoff_func): """3-body single-element kernel between two local energies accelerated with Numba. Args: bond_array_1 (np.ndarray): 3-body bond array of the first local environment. bond_array_2 (np.ndarray): 3-body bond array of the second local environment. cross_bond_inds_1 (np.ndarray): Two dimensional array whose row m contains the indices of atoms n > m in the first local environment that are within a distance r_cut of both atom n and the central atom. cross_bond_inds_2 (np.ndarray): Two dimensional array whose row m contains the indices of atoms n > m in the second local environment that are within a distance r_cut of both atom n and the central atom. cross_bond_dists_1 (np.ndarray): Two dimensional array whose row m contains the distances from atom m of atoms n > m in the first local environment that are within a distance r_cut of both atom n and the central atom. cross_bond_dists_2 (np.ndarray): Two dimensional array whose row m contains the distances from atom m of atoms n > m in the second local environment that are within a distance r_cut of both atom n and the central atom. triplets_1 (np.ndarray): One dimensional array of integers whose entry m is the number of atoms in the first local environment that are within a distance r_cut of atom m. triplets_2 (np.ndarray): One dimensional array of integers whose entry m is the number of atoms in the second local environment that are within a distance r_cut of atom m. sig (float): 3-body signal variance hyperparameter. ls (float): 3-body length scale hyperparameter. r_cut (float): 3-body cutoff radius. cutoff_func (Callable): Cutoff function. Returns: float: Value of the 3-body local energy kernel. """ kern = 0 sig2 = sig * sig ls2 = 1 / (2 * ls * ls) for m in range(bond_array_1.shape[0]): ri1 = bond_array_1[m, 0] fi1, _ = cutoff_func(r_cut, ri1, 0) for n in range(triplets_1[m]): ind1 = cross_bond_inds_1[m, m + n + 1] ri2 = bond_array_1[ind1, 0] fi2, _ = cutoff_func(r_cut, ri2, 0) ri3 = cross_bond_dists_1[m, m + n + 1] fi3, _ = cutoff_func(r_cut, ri3, 0) fi = fi1 * fi2 * fi3 for p in range(bond_array_2.shape[0]): rj1 = bond_array_2[p, 0] fj1, _ = cutoff_func(r_cut, rj1, 0) for q in range(triplets_2[p]): ind2 = cross_bond_inds_2[p, p + q + 1] rj2 = bond_array_2[ind2, 0] fj2, _ = cutoff_func(r_cut, rj2, 0) rj3 = cross_bond_dists_2[p, p + q + 1] fj3, _ = cutoff_func(r_cut, rj3, 0) fj = fj1 * fj2 * fj3 r11 = ri1 - rj1 r12 = ri1 - rj2 r13 = ri1 - rj3 r21 = ri2 - rj1 r22 = ri2 - rj2 r23 = ri2 - rj3 r31 = ri3 - rj1 r32 = ri3 - rj2 r33 = ri3 - rj3 C1 = r11 * r11 + r22 * r22 + r33 * r33 C2 = r11 * r11 + r23 * r23 + r32 * r32 C3 = r12 * r12 + r21 * r21 + r33 * r33 C4 = r12 * r12 + r23 * r23 + r31 * r31 C5 = r13 * r13 + r21 * r21 + r32 * r32 C6 = r13 * r13 + r22 * r22 + r31 * r31 k = exp(-C1 * ls2) + exp(-C2 * ls2) + exp(-C3 * ls2) + exp(-C4 * ls2) + \ exp(-C5 * ls2) + exp(-C6 * ls2) kern += sig2 * k * fi * fj return kern # ----------------------------------------------------------------------------- # many body numba functions # ----------------------------------------------------------------------------- @njit def many_body_jit(bond_array_1, bond_array_2, neighbouring_dists_array_1, neighbouring_dists_array_2, num_neighbours_1, num_neighbours_2, d1, d2, sig, ls, r_cut, cutoff_func): """many-body single-element kernel between two force components accelerated with Numba. Args: bond_array_1 (np.ndarray): many-body bond array of the first local environment. bond_array_2 (np.ndarray): many-body bond array of the second local environment. neighbouring_dists_array_1 (np.ndarray): matrix padded with zero values of distances of neighbours for the atoms in the first local environment. neighbouring_dists_array_2 (np.ndarray): matrix padded with zero values of distances of neighbours for the atoms in the second local environment. num_neighbours_1 (np.nsdarray): number of neighbours of each atom in the first local environment num_neighbours_2 (np.ndarray): number of neighbours of each atom in the second local environment d1 (int): Force component of the first environment. d2 (int): Force component of the second environment. sig (float): many-body signal variance hyperparameter. ls (float): many-body length scale hyperparameter. r_cut (float): many-body cutoff radius. cutoff_func (Callable): Cutoff function. Return: float: Value of the many-body kernel. """ kern = 0 # Calculate many-body descriptor values for 1 and 2 q1 = q_value(bond_array_1[:, 0], r_cut, cutoff_func) q2 = q_value(bond_array_2[:, 0], r_cut, cutoff_func) k12 = k_sq_exp_double_dev(q1, q2, sig, ls) qis = np.zeros(bond_array_1.shape[0], dtype=np.float64) qi1_grads = np.zeros(bond_array_1.shape[0], dtype=np.float64) ki2s = np.zeros(bond_array_1.shape[0], dtype=np.float64) qjs = np.zeros(bond_array_2.shape[0], dtype=np.float64) qj2_grads = np.zeros(bond_array_2.shape[0], dtype=np.float64) k1js = np.zeros(bond_array_2.shape[0], dtype=np.float64) # Loop over neighbours i of 1 for i in range(bond_array_1.shape[0]): ri1 = bond_array_1[i, 0] ci1 = bond_array_1[i, d1] qi1, qi1_grads[i] = coordination_number(ri1, ci1, r_cut, cutoff_func) # Calculate many-body descriptor value for i qis[i] = q_value(neighbouring_dists_array_1[i, :num_neighbours_1[i]], r_cut, cutoff_func) ki2s[i] = k_sq_exp_double_dev(qis[i], q2, sig, ls) # Loop over neighbours j of 2 for j in range(bond_array_2.shape[0]): rj2 = bond_array_2[j, 0] cj2 = bond_array_2[j, d2] qj2, qj2_grads[j] = coordination_number(rj2, cj2, r_cut, cutoff_func) # Calculate many-body descriptor value for j qjs[j] = q_value(neighbouring_dists_array_2[j, :num_neighbours_2[j]], r_cut, cutoff_func) k1js[j] = k_sq_exp_double_dev(q1, qjs[j], sig, ls) for i in range(bond_array_1.shape[0]): for j in range(bond_array_2.shape[0]): kij = k_sq_exp_double_dev(qis[i], qjs[j], sig, ls) kern += qi1_grads[i] * qj2_grads[j] * \ (k12 + ki2s[i] + k1js[j] + kij) return kern @njit def many_body_grad_jit(bond_array_1, bond_array_2, neighbouring_dists_array_1, neighbouring_dists_array_2, num_neighbours_1, num_neighbours_2, d1, d2, sig, ls, r_cut, cutoff_func): """gradient of many-body single-element kernel between two force components w.r.t. the hyperparameters, accelerated with Numba. Args: bond_array_1 (np.ndarray): many-body bond array of the first local environment. bond_array_2 (np.ndarray): many-body bond array of the second local environment. neighbouring_dists_array_1 (np.ndarray): matrix padded with zero values of distances of neighbours for the atoms in the first local environment. neighbouring_dists_array_2 (np.ndarray): matrix padded with zero values of distances of neighbours for the atoms in the second local environment. num_neighbours_1 (np.nsdarray): number of neighbours of each atom in the first local environment num_neighbours_2 (np.ndarray): number of neighbours of each atom in the second local environment d1 (int): Force component of the first environment. d2 (int): Force component of the second environment. sig (float): many-body signal variance hyperparameter. ls (float): many-body length scale hyperparameter. r_cut (float): many-body cutoff radius. cutoff_func (Callable): Cutoff function. Return: array: Value of the many-body kernel and its gradient w.r.t. sig and ls """ kern = 0 sig_derv = 0 ls_derv = 0 # Calculate many-body descriptor values for 1 and 2 q1 = q_value(bond_array_1[:, 0], r_cut, cutoff_func) q2 = q_value(bond_array_2[:, 0], r_cut, cutoff_func) k12 = k_sq_exp_double_dev(q1, q2, sig, ls) qis = np.zeros(bond_array_1.shape[0], dtype=np.float64) qi1_grads = np.zeros(bond_array_1.shape[0], dtype=np.float64) ki2s = np.zeros(bond_array_1.shape[0], dtype=np.float64) qjs = np.zeros(bond_array_2.shape[0], dtype=np.float64) qj2_grads = np.zeros(bond_array_2.shape[0], dtype=np.float64) k1js = np.zeros(bond_array_2.shape[0], dtype=np.float64) # Compute ki2s, qi1_grads, and qis for i in range(bond_array_1.shape[0]): ri1 = bond_array_1[i, 0] ci1 = bond_array_1[i, d1] qi1, qi1_grads[i] = coordination_number(ri1, ci1, r_cut, cutoff_func) # Calculate many-body descriptor value for i qis[i] = q_value(neighbouring_dists_array_1[i, :num_neighbours_1[i]], r_cut, cutoff_func) ki2s[i] = k_sq_exp_double_dev(qis[i], q2, sig, ls) # Compute k1js, qj2_grads and qjs for j in range(bond_array_2.shape[0]): rj2 = bond_array_2[j, 0] cj2 = bond_array_2[j, d2] qj2, qj2_grads[j] = coordination_number(rj2, cj2, r_cut, cutoff_func) # Calculate many-body descriptor value for j qjs[j] = q_value(neighbouring_dists_array_2[j, :num_neighbours_2[j]], r_cut, cutoff_func) k1js[j] = k_sq_exp_double_dev(q1, qjs[j], sig, ls) for i in range(bond_array_1.shape[0]): for j in range(bond_array_2.shape[0]): kij = k_sq_exp_double_dev(qis[i], qjs[j], sig, ls) kern_term = qi1_grads[i] * qj2_grads[j] * \ (k12 + ki2s[i] + k1js[j] + kij) sig_term = 2. / sig * kern_term ls_term = qi1_grads[i] * qj2_grads[j] * mb_grad_helper_ls(q1, q2, qis[i], qjs[j], sig, ls) kern += kern_term sig_derv += sig_term ls_derv += ls_term # sig_derv = 2./sig * kern return kern, sig_derv, ls_derv @njit def many_body_force_en_jit(bond_array_1, bond_array_2, neighbouring_dists_array_1, num_neighbours_1, d1, sig, ls, r_cut, cutoff_func): """many-body single-element kernel between force and energy components accelerated with Numba. Args: bond_array_1 (np.ndarray): many-body bond array of the first local environment. bond_array_2 (np.ndarray): many-body bond array of the second local environment. neighbouring_dists_array_1 (np.ndarray): matrix padded with zero values of distances of neighbours for the atoms in the first local environment. num_neighbours_1 (np.nsdarray): number of neighbours of each atom in the first local environment d1 (int): Force component of the first environment. sig (float): many-body signal variance hyperparameter. ls (float): many-body length scale hyperparameter. r_cut (float): many-body cutoff radius. cutoff_func (Callable): Cutoff function. Return: float: Value of the many-body kernel. """ kern = 0 q1 = q_value(bond_array_1[:, 0], r_cut, cutoff_func) q2 = q_value(bond_array_2[:, 0], r_cut, cutoff_func) k12 = k_sq_exp_dev(q1, q2, sig, ls) qis = np.zeros(bond_array_1.shape[0], dtype=np.float64) qi1_grads = np.zeros(bond_array_1.shape[0], dtype=np.float64) ki2s = np.zeros(bond_array_1.shape[0], dtype=np.float64) # Loop over neighbours i of 1 for i in range(bond_array_1.shape[0]): ri1 = bond_array_1[i, 0] ci1 = bond_array_1[i, d1] _, qi1_grads[i] = coordination_number(ri1, ci1, r_cut, cutoff_func) # Calculate many-body descriptor value for i qis[i] = q_value(neighbouring_dists_array_1[i, :num_neighbours_1[i]], r_cut, cutoff_func) ki2s[i] = k_sq_exp_dev(qis[i], q2, sig, ls) kern += - qi1_grads[i] * (k12 + ki2s[i]) return kern @njit def many_body_en_jit(bond_array_1, bond_array_2, sig, ls, r_cut, cutoff_func): """many-body single-element energy kernel between accelerated with Numba. Args: bond_array_1 (np.ndarray): many-body bond array of the first local environment. bond_array_2 (np.ndarray): many-body bond array of the second local environment. neighbouring_dists_array_1 (np.ndarray): matrix padded with zero values of distances of neighbours for the atoms in the first local environment. neighbouring_dists_array_2 (np.ndarray): matrix padded with zero values of distances of neighbours for the atoms in the second local environment. num_neighbours_1 (np.nsdarray): number of neighbours of each atom in the first local environment num_neighbours_2 (np.ndarray): number of neighbours of each atom in the second local environment d1 (int): Force component of the first environment. d2 (int): Force component of the second environment. sig (float): many-body signal variance hyperparameter. ls (float): many-body length scale hyperparameter. r_cut (float): many-body cutoff radius. cutoff_func (Callable): Cutoff function. Return: float: Value of the many-body kernel. """ q1 = q_value(bond_array_1[:, 0], r_cut, cutoff_func) q2 = q_value(bond_array_2[:, 0], r_cut, cutoff_func) q1q2diff = q1 - q2 kern = sig * sig * exp(-q1q2diff * q1q2diff / (2 * ls * ls)) return kern # ----------------------------------------------------------------------------- # three body helper functions # ----------------------------------------------------------------------------- @njit def triplet_kernel(ci1, ci2, cj1, cj2, ri1, ri2, ri3, rj1, rj2, rj3, fi, fj, fdi, fdj, ls1, ls2, ls3, sig2): r11 = ri1 - rj1 r12 = ri1 - rj2 r13 = ri1 - rj3 r21 = ri2 - rj1 r22 = ri2 - rj2 r23 = ri2 - rj3 r31 = ri3 - rj1 r32 = ri3 - rj2 r33 = ri3 - rj3 # sum over all six permutations M1 = three_body_helper_1(ci1, ci2, cj1, cj2, r11, r22, r33, fi, fj, fdi, fdj, ls1, ls2, ls3, sig2) M2 = three_body_helper_2(ci2, ci1, cj2, cj1, r21, r13, r32, fi, fj, fdi, fdj, ls1, ls2, ls3, sig2) M3 = three_body_helper_2(ci1, ci2, cj1, cj2, r12, r23, r31, fi, fj, fdi, fdj, ls1, ls2, ls3, sig2) M4 = three_body_helper_1(ci1, ci2, cj2, cj1, r12, r21, r33, fi, fj, fdi, fdj, ls1, ls2, ls3, sig2) M5 = three_body_helper_2(ci2, ci1, cj1, cj2, r22, r13, r31, fi, fj, fdi, fdj, ls1, ls2, ls3, sig2) M6 = three_body_helper_2(ci1, ci2, cj2, cj1, r11, r23, r32, fi, fj, fdi, fdj, ls1, ls2, ls3, sig2) return M1 + M2 + M3 + M4 + M5 + M6 @njit def triplet_kernel_grad(ci1, ci2, cj1, cj2, ri1, ri2, ri3, rj1, rj2, rj3, fi, fj, fdi, fdj, ls1, ls2, ls3, ls4, ls5, ls6, sig2, sig3): r11 = ri1 - rj1 r12 = ri1 - rj2 r13 = ri1 - rj3 r21 = ri2 - rj1 r22 = ri2 - rj2 r23 = ri2 - rj3 r31 = ri3 - rj1 r32 = ri3 - rj2 r33 = ri3 - rj3 N1, O1, X1 = \ three_body_grad_helper_1(ci1, ci2, cj1, cj2, r11, r22, r33, fi, fj, fdi, fdj, ls1, ls2, ls3, ls4, ls5, ls6, sig2, sig3) N2, O2, X2 = \ three_body_grad_helper_2(ci2, ci1, cj2, cj1, r21, r13, r32, fi, fj, fdi, fdj, ls1, ls2, ls3, ls4, ls5, ls6, sig2, sig3) N3, O3, X3 = \ three_body_grad_helper_2(ci1, ci2, cj1, cj2, r12, r23, r31, fi, fj, fdi, fdj, ls1, ls2, ls3, ls4, ls5, ls6, sig2, sig3) N4, O4, X4 = \ three_body_grad_helper_1(ci1, ci2, cj2, cj1, r12, r21, r33, fi, fj, fdi, fdj, ls1, ls2, ls3, ls4, ls5, ls6, sig2, sig3) N5, O5, X5 = \ three_body_grad_helper_2(ci2, ci1, cj1, cj2, r22, r13, r31, fi, fj, fdi, fdj, ls1, ls2, ls3, ls4, ls5, ls6, sig2, sig3) N6, O6, X6 = \ three_body_grad_helper_2(ci1, ci2, cj2, cj1, r11, r23, r32, fi, fj, fdi, fdj, ls1, ls2, ls3, ls4, ls5, ls6, sig2, sig3) N = N1 + N2 + N3 + N4 + N5 + N6 O = O1 + O2 + O3 + O4 + O5 + O6 X = X1 + X2 + X3 + X4 + X5 + X6 return N, O, X @njit def triplet_force_en_kernel(ci1, ci2, ri1, ri2, ri3, rj1, rj2, rj3, fi, fj, fdi, ls1, ls2, sig2): r11 = ri1 - rj1 r12 = ri1 - rj2 r13 = ri1 - rj3 r21 = ri2 - rj1 r22 = ri2 - rj2 r23 = ri2 - rj3 r31 = ri3 - rj1 r32 = ri3 - rj2 r33 = ri3 - rj3 I1 = three_body_en_helper(ci1, ci2, r11, r22, r33, fi, fj, fdi, ls1, ls2, sig2) I2 = three_body_en_helper(ci1, ci2, r13, r21, r32, fi, fj, fdi, ls1, ls2, sig2) I3 = three_body_en_helper(ci1, ci2, r12, r23, r31, fi, fj, fdi, ls1, ls2, sig2) I4 = three_body_en_helper(ci1, ci2, r12, r21, r33, fi, fj, fdi, ls1, ls2, sig2) I5 = three_body_en_helper(ci1, ci2, r13, r22, r31, fi, fj, fdi, ls1, ls2, sig2) I6 = three_body_en_helper(ci1, ci2, r11, r23, r32, fi, fj, fdi, ls1, ls2, sig2) return I1 + I2 + I3 + I4 + I5 + I6 # ----------------------------------------------------------------------------- # many body helper functions # ----------------------------------------------------------------------------- @njit def k_sq_exp_double_dev(q1, q2, sig, ls): """Second Gradient of generic squared exponential kernel on two many body functions Args: q1 (float): the many body descriptor of the first local environment q2 (float): the many body descriptor of the second local environment sig (float): amplitude hyperparameter ls2 (float): squared lenghtscale hyperparameter Return: float: the value of the double derivative of the squared exponential kernel """ qdiffsq = (q1 - q2) * (q1 - q2) ls2 = ls * ls ker = exp(-qdiffsq / (2 * ls2)) ret = sig * sig * ker / ls2 * (1 - qdiffsq / ls2) return ret @njit def k_sq_exp_dev(q1, q2, sig, ls): """Second Gradient of generic squared exponential kernel on two many body functions Args: q1 (float): the many body descriptor of the first local environment q2 (float): the many body descriptor of the second local environment sig (float): amplitude hyperparameter ls2 (float): squared lenghtscale hyperparameter Return: float: the value of the derivative of the squared exponential kernel """ qdiff = (q1 - q2) ls2 = ls * ls ker = exp(-qdiff * qdiff / (2 * ls2)) ret = - sig * sig * ker / ls2 * qdiff return ret @njit def coordination_number(rij, cij, r_cut, cutoff_func): """Pairwise contribution to many-body descriptor based on number of atoms in the environment Args: rij (float): distance between atoms i and j cij (float): Component of versor of rij along given direction r_cut (float): cutoff hyperparameter cutoff_func (callable): cutoff function Return: float: the value of the pairwise many-body contribution float: the value of the derivative of the pairwise many-body contribution w.r.t. the central atom displacement """ fij, fdij = cutoff_func(r_cut, rij, cij) return fij, fdij @njit def q_value(distances, r_cut, cutoff_func, q_func=coordination_number): """Compute value of many-body descriptor based on distances of atoms in the local amny-body environment. Args: distances (np.ndarray): distances between atoms i and j r_cut (float): cutoff hyperparameter cutoff_func (callable): cutoff function q_func (callable): many-body pairwise descrptor function Return: float: the value of the many-body descriptor """ q = 0 for d in distances: q_, _ = q_func(d, 0, r_cut, cutoff_func) q += q_ return q @njit def mb_grad_helper_ls_(qdiffsq, sig, ls): """Derivative of a many body force-force kernel wrt ls """ ls2 = ls * ls prefact = exp(-(qdiffsq / (2 * ls2))) * (sig * sig) / ls ** 5 ret = - prefact * (qdiffsq ** 2 / ls2 - 5 * qdiffsq + 2 * ls2) return ret @njit def mb_grad_helper_ls(q1, q2, qi, qj, sig, ls): """Helper function fr many body gradient collecting all the derivatives of the force-foce many body kernel wrt ls """ q12diffsq = ((q1 - q2) * (q1 - q2)) qijdiffsq = ((qi - qj) * (qi - qj)) qi2diffsq = ((qi - q2) * (qi - q2)) q1jdiffsq = ((q1 - qj) * (q1 - qj)) dk12 = mb_grad_helper_ls_(q12diffsq, sig, ls) dkij = mb_grad_helper_ls_(qijdiffsq, sig, ls) dki2 = mb_grad_helper_ls_(qi2diffsq, sig, ls) dk1j = mb_grad_helper_ls_(q1jdiffsq, sig, ls) return dk12 + dkij + dki2 + dk1j _str_to_kernel = {'two_body': two_body, 'two_body_en': two_body_en, 'two_body_force_en': two_body_force_en, 'three_body': three_body, 'three_body_en': three_body_en, 'three_body_force_en': three_body_force_en, 'two_plus_three_body': two_plus_three_body, 'two_plus_three_en': two_plus_three_en, 'two_plus_three_force_en': two_plus_three_force_en, '2': two_body, '2_en': two_body_en, '2_grad': two_body_grad, '2_force_en': two_body_force_en, '3': three_body, '3_grad': three_body_grad, '3_en': three_body_en, '3_force_en': three_body_force_en, '2+3': two_plus_three_body, '2+3_grad': two_plus_three_body_grad, '2+3_en': two_plus_three_en, '2+3_force_en': two_plus_three_force_en, 'many': many_body, 'many_en': many_body_en, 'many_grad': many_body_grad, 'many_force_en': many_body_force_en, 'two_plus_three_plus_many_body': two_plus_three_plus_many_body, 'two_plus_three_plus_many_body_grad': two_plus_three_plus_many_body_grad, 'two_plus_three_plus_many_body_en': two_plus_three_plus_many_body_en, 'two_plus_three_plus_many_body_force_en': two_plus_three_plus_many_body_force_en, '2+3+many': two_plus_three_plus_many_body, '2+3+many_grad': two_plus_three_plus_many_body_grad, '2+3+many_en': two_plus_three_plus_many_body_en, '2+3+many_force_en': two_plus_three_plus_many_body_force_en } def str_to_kernel(string: str, include_grad: bool = False): if string not in _str_to_kernel.keys(): raise ValueError("Kernel {} not found in list of available " "kernels{}:".format(string, _str_to_kernel.keys())) if not include_grad: return _str_to_kernel[string] else: if 'two' in string and 'three' in string: return _str_to_kernel[string], two_plus_three_body_grad elif 'two' in string and 'three' not in string: return _str_to_kernel[string], two_body_grad elif 'two' not in string and 'three' in string: return _str_to_kernel[string], three_body_grad else: raise ValueError("Gradient callable for {} not found".format( string))
[ "math.exp", "flare.kernels.kernels.three_body_en_helper", "flare.kernels.kernels.three_body_grad_helper_2", "flare.kernels.kernels.force_helper", "flare.kernels.kernels.force_energy_helper", "numpy.zeros", "numpy.array", "flare.kernels.kernels.grad_helper", "flare.kernels.kernels.three_body_helper_1...
[((16441, 16470), 'numpy.array', 'np.array', (['[sig_derv, ls_derv]'], {}), '([sig_derv, ls_derv])\n', (16449, 16470), True, 'import numpy as np\n'), ((21044, 21073), 'numpy.array', 'np.array', (['[sig_derv, ls_derv]'], {}), '([sig_derv, ls_derv])\n', (21052, 21073), True, 'import numpy as np\n'), ((26356, 26385), 'numpy.array', 'np.array', (['[sig_derv, ls_derv]'], {}), '([sig_derv, ls_derv])\n', (26364, 26385), True, 'import numpy as np\n'), ((31017, 31040), 'flare.kernels.kernels.grad_constants', 'grad_constants', (['sig', 'ls'], {}), '(sig, ls)\n', (31031, 31040), False, 'from flare.kernels.kernels import force_helper, grad_constants, grad_helper, force_energy_helper, three_body_en_helper, three_body_helper_1, three_body_helper_2, three_body_grad_helper_1, three_body_grad_helper_2\n'), ((41194, 41217), 'flare.kernels.kernels.grad_constants', 'grad_constants', (['sig', 'ls'], {}), '(sig, ls)\n', (41208, 41217), False, 'from flare.kernels.kernels import force_helper, grad_constants, grad_helper, force_energy_helper, three_body_en_helper, three_body_helper_1, three_body_helper_2, three_body_grad_helper_1, three_body_grad_helper_2\n'), ((53106, 53155), 'numpy.zeros', 'np.zeros', (['bond_array_1.shape[0]'], {'dtype': 'np.float64'}), '(bond_array_1.shape[0], dtype=np.float64)\n', (53114, 53155), True, 'import numpy as np\n'), ((53172, 53221), 'numpy.zeros', 'np.zeros', (['bond_array_1.shape[0]'], {'dtype': 'np.float64'}), '(bond_array_1.shape[0], dtype=np.float64)\n', (53180, 53221), True, 'import numpy as np\n'), ((53233, 53282), 'numpy.zeros', 'np.zeros', (['bond_array_1.shape[0]'], {'dtype': 'np.float64'}), '(bond_array_1.shape[0], dtype=np.float64)\n', (53241, 53282), True, 'import numpy as np\n'), ((53294, 53343), 'numpy.zeros', 'np.zeros', (['bond_array_2.shape[0]'], {'dtype': 'np.float64'}), '(bond_array_2.shape[0], dtype=np.float64)\n', (53302, 53343), True, 'import numpy as np\n'), ((53360, 53409), 'numpy.zeros', 'np.zeros', (['bond_array_2.shape[0]'], {'dtype': 'np.float64'}), '(bond_array_2.shape[0], dtype=np.float64)\n', (53368, 53409), True, 'import numpy as np\n'), ((53421, 53470), 'numpy.zeros', 'np.zeros', (['bond_array_2.shape[0]'], {'dtype': 'np.float64'}), '(bond_array_2.shape[0], dtype=np.float64)\n', (53429, 53470), True, 'import numpy as np\n'), ((56551, 56600), 'numpy.zeros', 'np.zeros', (['bond_array_1.shape[0]'], {'dtype': 'np.float64'}), '(bond_array_1.shape[0], dtype=np.float64)\n', (56559, 56600), True, 'import numpy as np\n'), ((56618, 56667), 'numpy.zeros', 'np.zeros', (['bond_array_1.shape[0]'], {'dtype': 'np.float64'}), '(bond_array_1.shape[0], dtype=np.float64)\n', (56626, 56667), True, 'import numpy as np\n'), ((56680, 56729), 'numpy.zeros', 'np.zeros', (['bond_array_1.shape[0]'], {'dtype': 'np.float64'}), '(bond_array_1.shape[0], dtype=np.float64)\n', (56688, 56729), True, 'import numpy as np\n'), ((56741, 56790), 'numpy.zeros', 'np.zeros', (['bond_array_2.shape[0]'], {'dtype': 'np.float64'}), '(bond_array_2.shape[0], dtype=np.float64)\n', (56749, 56790), True, 'import numpy as np\n'), ((56808, 56857), 'numpy.zeros', 'np.zeros', (['bond_array_2.shape[0]'], {'dtype': 'np.float64'}), '(bond_array_2.shape[0], dtype=np.float64)\n', (56816, 56857), True, 'import numpy as np\n'), ((56870, 56919), 'numpy.zeros', 'np.zeros', (['bond_array_2.shape[0]'], {'dtype': 'np.float64'}), '(bond_array_2.shape[0], dtype=np.float64)\n', (56878, 56919), True, 'import numpy as np\n'), ((59841, 59890), 'numpy.zeros', 'np.zeros', (['bond_array_1.shape[0]'], {'dtype': 'np.float64'}), '(bond_array_1.shape[0], dtype=np.float64)\n', (59849, 59890), True, 'import numpy as np\n'), ((59907, 59956), 'numpy.zeros', 'np.zeros', (['bond_array_1.shape[0]'], {'dtype': 'np.float64'}), '(bond_array_1.shape[0], dtype=np.float64)\n', (59915, 59956), True, 'import numpy as np\n'), ((59968, 60017), 'numpy.zeros', 'np.zeros', (['bond_array_1.shape[0]'], {'dtype': 'np.float64'}), '(bond_array_1.shape[0], dtype=np.float64)\n', (59976, 60017), True, 'import numpy as np\n'), ((62707, 62804), 'flare.kernels.kernels.three_body_helper_1', 'three_body_helper_1', (['ci1', 'ci2', 'cj1', 'cj2', 'r11', 'r22', 'r33', 'fi', 'fj', 'fdi', 'fdj', 'ls1', 'ls2', 'ls3', 'sig2'], {}), '(ci1, ci2, cj1, cj2, r11, r22, r33, fi, fj, fdi, fdj,\n ls1, ls2, ls3, sig2)\n', (62726, 62804), False, 'from flare.kernels.kernels import force_helper, grad_constants, grad_helper, force_energy_helper, three_body_en_helper, three_body_helper_1, three_body_helper_2, three_body_grad_helper_1, three_body_grad_helper_2\n'), ((62839, 62936), 'flare.kernels.kernels.three_body_helper_2', 'three_body_helper_2', (['ci2', 'ci1', 'cj2', 'cj1', 'r21', 'r13', 'r32', 'fi', 'fj', 'fdi', 'fdj', 'ls1', 'ls2', 'ls3', 'sig2'], {}), '(ci2, ci1, cj2, cj1, r21, r13, r32, fi, fj, fdi, fdj,\n ls1, ls2, ls3, sig2)\n', (62858, 62936), False, 'from flare.kernels.kernels import force_helper, grad_constants, grad_helper, force_energy_helper, three_body_en_helper, three_body_helper_1, three_body_helper_2, three_body_grad_helper_1, three_body_grad_helper_2\n'), ((62971, 63068), 'flare.kernels.kernels.three_body_helper_2', 'three_body_helper_2', (['ci1', 'ci2', 'cj1', 'cj2', 'r12', 'r23', 'r31', 'fi', 'fj', 'fdi', 'fdj', 'ls1', 'ls2', 'ls3', 'sig2'], {}), '(ci1, ci2, cj1, cj2, r12, r23, r31, fi, fj, fdi, fdj,\n ls1, ls2, ls3, sig2)\n', (62990, 63068), False, 'from flare.kernels.kernels import force_helper, grad_constants, grad_helper, force_energy_helper, three_body_en_helper, three_body_helper_1, three_body_helper_2, three_body_grad_helper_1, three_body_grad_helper_2\n'), ((63103, 63200), 'flare.kernels.kernels.three_body_helper_1', 'three_body_helper_1', (['ci1', 'ci2', 'cj2', 'cj1', 'r12', 'r21', 'r33', 'fi', 'fj', 'fdi', 'fdj', 'ls1', 'ls2', 'ls3', 'sig2'], {}), '(ci1, ci2, cj2, cj1, r12, r21, r33, fi, fj, fdi, fdj,\n ls1, ls2, ls3, sig2)\n', (63122, 63200), False, 'from flare.kernels.kernels import force_helper, grad_constants, grad_helper, force_energy_helper, three_body_en_helper, three_body_helper_1, three_body_helper_2, three_body_grad_helper_1, three_body_grad_helper_2\n'), ((63235, 63332), 'flare.kernels.kernels.three_body_helper_2', 'three_body_helper_2', (['ci2', 'ci1', 'cj1', 'cj2', 'r22', 'r13', 'r31', 'fi', 'fj', 'fdi', 'fdj', 'ls1', 'ls2', 'ls3', 'sig2'], {}), '(ci2, ci1, cj1, cj2, r22, r13, r31, fi, fj, fdi, fdj,\n ls1, ls2, ls3, sig2)\n', (63254, 63332), False, 'from flare.kernels.kernels import force_helper, grad_constants, grad_helper, force_energy_helper, three_body_en_helper, three_body_helper_1, three_body_helper_2, three_body_grad_helper_1, three_body_grad_helper_2\n'), ((63367, 63464), 'flare.kernels.kernels.three_body_helper_2', 'three_body_helper_2', (['ci1', 'ci2', 'cj2', 'cj1', 'r11', 'r23', 'r32', 'fi', 'fj', 'fdi', 'fdj', 'ls1', 'ls2', 'ls3', 'sig2'], {}), '(ci1, ci2, cj2, cj1, r11, r23, r32, fi, fj, fdi, fdj,\n ls1, ls2, ls3, sig2)\n', (63386, 63464), False, 'from flare.kernels.kernels import force_helper, grad_constants, grad_helper, force_energy_helper, three_body_en_helper, three_body_helper_1, three_body_helper_2, three_body_grad_helper_1, three_body_grad_helper_2\n'), ((63929, 64052), 'flare.kernels.kernels.three_body_grad_helper_1', 'three_body_grad_helper_1', (['ci1', 'ci2', 'cj1', 'cj2', 'r11', 'r22', 'r33', 'fi', 'fj', 'fdi', 'fdj', 'ls1', 'ls2', 'ls3', 'ls4', 'ls5', 'ls6', 'sig2', 'sig3'], {}), '(ci1, ci2, cj1, cj2, r11, r22, r33, fi, fj, fdi,\n fdj, ls1, ls2, ls3, ls4, ls5, ls6, sig2, sig3)\n', (63953, 64052), False, 'from flare.kernels.kernels import force_helper, grad_constants, grad_helper, force_energy_helper, three_body_en_helper, three_body_helper_1, three_body_helper_2, three_body_grad_helper_1, three_body_grad_helper_2\n'), ((64142, 64265), 'flare.kernels.kernels.three_body_grad_helper_2', 'three_body_grad_helper_2', (['ci2', 'ci1', 'cj2', 'cj1', 'r21', 'r13', 'r32', 'fi', 'fj', 'fdi', 'fdj', 'ls1', 'ls2', 'ls3', 'ls4', 'ls5', 'ls6', 'sig2', 'sig3'], {}), '(ci2, ci1, cj2, cj1, r21, r13, r32, fi, fj, fdi,\n fdj, ls1, ls2, ls3, ls4, ls5, ls6, sig2, sig3)\n', (64166, 64265), False, 'from flare.kernels.kernels import force_helper, grad_constants, grad_helper, force_energy_helper, three_body_en_helper, three_body_helper_1, three_body_helper_2, three_body_grad_helper_1, three_body_grad_helper_2\n'), ((64355, 64478), 'flare.kernels.kernels.three_body_grad_helper_2', 'three_body_grad_helper_2', (['ci1', 'ci2', 'cj1', 'cj2', 'r12', 'r23', 'r31', 'fi', 'fj', 'fdi', 'fdj', 'ls1', 'ls2', 'ls3', 'ls4', 'ls5', 'ls6', 'sig2', 'sig3'], {}), '(ci1, ci2, cj1, cj2, r12, r23, r31, fi, fj, fdi,\n fdj, ls1, ls2, ls3, ls4, ls5, ls6, sig2, sig3)\n', (64379, 64478), False, 'from flare.kernels.kernels import force_helper, grad_constants, grad_helper, force_energy_helper, three_body_en_helper, three_body_helper_1, three_body_helper_2, three_body_grad_helper_1, three_body_grad_helper_2\n'), ((64568, 64691), 'flare.kernels.kernels.three_body_grad_helper_1', 'three_body_grad_helper_1', (['ci1', 'ci2', 'cj2', 'cj1', 'r12', 'r21', 'r33', 'fi', 'fj', 'fdi', 'fdj', 'ls1', 'ls2', 'ls3', 'ls4', 'ls5', 'ls6', 'sig2', 'sig3'], {}), '(ci1, ci2, cj2, cj1, r12, r21, r33, fi, fj, fdi,\n fdj, ls1, ls2, ls3, ls4, ls5, ls6, sig2, sig3)\n', (64592, 64691), False, 'from flare.kernels.kernels import force_helper, grad_constants, grad_helper, force_energy_helper, three_body_en_helper, three_body_helper_1, three_body_helper_2, three_body_grad_helper_1, three_body_grad_helper_2\n'), ((64781, 64904), 'flare.kernels.kernels.three_body_grad_helper_2', 'three_body_grad_helper_2', (['ci2', 'ci1', 'cj1', 'cj2', 'r22', 'r13', 'r31', 'fi', 'fj', 'fdi', 'fdj', 'ls1', 'ls2', 'ls3', 'ls4', 'ls5', 'ls6', 'sig2', 'sig3'], {}), '(ci2, ci1, cj1, cj2, r22, r13, r31, fi, fj, fdi,\n fdj, ls1, ls2, ls3, ls4, ls5, ls6, sig2, sig3)\n', (64805, 64904), False, 'from flare.kernels.kernels import force_helper, grad_constants, grad_helper, force_energy_helper, three_body_en_helper, three_body_helper_1, three_body_helper_2, three_body_grad_helper_1, three_body_grad_helper_2\n'), ((64994, 65117), 'flare.kernels.kernels.three_body_grad_helper_2', 'three_body_grad_helper_2', (['ci1', 'ci2', 'cj2', 'cj1', 'r11', 'r23', 'r32', 'fi', 'fj', 'fdi', 'fdj', 'ls1', 'ls2', 'ls3', 'ls4', 'ls5', 'ls6', 'sig2', 'sig3'], {}), '(ci1, ci2, cj2, cj1, r11, r23, r32, fi, fj, fdi,\n fdj, ls1, ls2, ls3, ls4, ls5, ls6, sig2, sig3)\n', (65018, 65117), False, 'from flare.kernels.kernels import force_helper, grad_constants, grad_helper, force_energy_helper, three_body_en_helper, three_body_helper_1, three_body_helper_2, three_body_grad_helper_1, three_body_grad_helper_2\n'), ((65632, 65706), 'flare.kernels.kernels.three_body_en_helper', 'three_body_en_helper', (['ci1', 'ci2', 'r11', 'r22', 'r33', 'fi', 'fj', 'fdi', 'ls1', 'ls2', 'sig2'], {}), '(ci1, ci2, r11, r22, r33, fi, fj, fdi, ls1, ls2, sig2)\n', (65652, 65706), False, 'from flare.kernels.kernels import force_helper, grad_constants, grad_helper, force_energy_helper, three_body_en_helper, three_body_helper_1, three_body_helper_2, three_body_grad_helper_1, three_body_grad_helper_2\n'), ((65746, 65820), 'flare.kernels.kernels.three_body_en_helper', 'three_body_en_helper', (['ci1', 'ci2', 'r13', 'r21', 'r32', 'fi', 'fj', 'fdi', 'ls1', 'ls2', 'sig2'], {}), '(ci1, ci2, r13, r21, r32, fi, fj, fdi, ls1, ls2, sig2)\n', (65766, 65820), False, 'from flare.kernels.kernels import force_helper, grad_constants, grad_helper, force_energy_helper, three_body_en_helper, three_body_helper_1, three_body_helper_2, three_body_grad_helper_1, three_body_grad_helper_2\n'), ((65860, 65934), 'flare.kernels.kernels.three_body_en_helper', 'three_body_en_helper', (['ci1', 'ci2', 'r12', 'r23', 'r31', 'fi', 'fj', 'fdi', 'ls1', 'ls2', 'sig2'], {}), '(ci1, ci2, r12, r23, r31, fi, fj, fdi, ls1, ls2, sig2)\n', (65880, 65934), False, 'from flare.kernels.kernels import force_helper, grad_constants, grad_helper, force_energy_helper, three_body_en_helper, three_body_helper_1, three_body_helper_2, three_body_grad_helper_1, three_body_grad_helper_2\n'), ((65974, 66048), 'flare.kernels.kernels.three_body_en_helper', 'three_body_en_helper', (['ci1', 'ci2', 'r12', 'r21', 'r33', 'fi', 'fj', 'fdi', 'ls1', 'ls2', 'sig2'], {}), '(ci1, ci2, r12, r21, r33, fi, fj, fdi, ls1, ls2, sig2)\n', (65994, 66048), False, 'from flare.kernels.kernels import force_helper, grad_constants, grad_helper, force_energy_helper, three_body_en_helper, three_body_helper_1, three_body_helper_2, three_body_grad_helper_1, three_body_grad_helper_2\n'), ((66088, 66162), 'flare.kernels.kernels.three_body_en_helper', 'three_body_en_helper', (['ci1', 'ci2', 'r13', 'r22', 'r31', 'fi', 'fj', 'fdi', 'ls1', 'ls2', 'sig2'], {}), '(ci1, ci2, r13, r22, r31, fi, fj, fdi, ls1, ls2, sig2)\n', (66108, 66162), False, 'from flare.kernels.kernels import force_helper, grad_constants, grad_helper, force_energy_helper, three_body_en_helper, three_body_helper_1, three_body_helper_2, three_body_grad_helper_1, three_body_grad_helper_2\n'), ((66202, 66276), 'flare.kernels.kernels.three_body_en_helper', 'three_body_en_helper', (['ci1', 'ci2', 'r11', 'r23', 'r32', 'fi', 'fj', 'fdi', 'ls1', 'ls2', 'sig2'], {}), '(ci1, ci2, r11, r23, r32, fi, fj, fdi, ls1, ls2, sig2)\n', (66222, 66276), False, 'from flare.kernels.kernels import force_helper, grad_constants, grad_helper, force_energy_helper, three_body_en_helper, three_body_helper_1, three_body_helper_2, three_body_grad_helper_1, three_body_grad_helper_2\n'), ((67135, 67160), 'math.exp', 'exp', (['(-qdiffsq / (2 * ls2))'], {}), '(-qdiffsq / (2 * ls2))\n', (67138, 67160), False, 'from math import exp\n'), ((67780, 67811), 'math.exp', 'exp', (['(-qdiff * qdiff / (2 * ls2))'], {}), '(-qdiff * qdiff / (2 * ls2))\n', (67783, 67811), False, 'from math import exp\n'), ((4267, 4299), 'numpy.array', 'np.array', (['[sig2, ls2, sig3, ls3]'], {}), '([sig2, ls2, sig3, ls3])\n', (4275, 4299), True, 'import numpy as np\n'), ((10890, 10933), 'numpy.array', 'np.array', (['[sig2, ls2, sig3, ls3, sigm, lsm]'], {}), '([sig2, ls2, sig3, ls3, sigm, lsm])\n', (10898, 10933), True, 'import numpy as np\n'), ((62072, 62113), 'math.exp', 'exp', (['(-q1q2diff * q1q2diff / (2 * ls * ls))'], {}), '(-q1q2diff * q1q2diff / (2 * ls * ls))\n', (62075, 62113), False, 'from math import exp\n'), ((29847, 29910), 'flare.kernels.kernels.force_helper', 'force_helper', (['A', 'B', 'C', 'D', 'fi', 'fj', 'fdi', 'fdj', 'ls1', 'ls2', 'ls3', 'sig2'], {}), '(A, B, C, D, fi, fj, fdi, fdj, ls1, ls2, ls3, sig2)\n', (29859, 29910), False, 'from flare.kernels.kernels import force_helper, grad_constants, grad_helper, force_energy_helper, three_body_en_helper, three_body_helper_1, three_body_helper_2, three_body_grad_helper_1, three_body_grad_helper_2\n'), ((31555, 31642), 'flare.kernels.kernels.grad_helper', 'grad_helper', (['A', 'B', 'C', 'D', 'fi', 'fj', 'fdi', 'fdj', 'ls1', 'ls2', 'ls3', 'ls4', 'ls5', 'ls6', 'sig2', 'sig3'], {}), '(A, B, C, D, fi, fj, fdi, fdj, ls1, ls2, ls3, ls4, ls5, ls6,\n sig2, sig3)\n', (31566, 31642), False, 'from flare.kernels.kernels import force_helper, grad_constants, grad_helper, force_energy_helper, three_body_en_helper, three_body_helper_1, three_body_helper_2, three_body_grad_helper_1, three_body_grad_helper_2\n'), ((33080, 33134), 'flare.kernels.kernels.force_energy_helper', 'force_energy_helper', (['B', 'D', 'fi', 'fj', 'fdi', 'ls1', 'ls2', 'sig2'], {}), '(B, D, fi, fj, fdi, ls1, ls2, sig2)\n', (33099, 33134), False, 'from flare.kernels.kernels import force_helper, grad_constants, grad_helper, force_energy_helper, three_body_en_helper, three_body_helper_1, three_body_helper_2, three_body_grad_helper_1, three_body_grad_helper_2\n'), ((69310, 69337), 'math.exp', 'exp', (['(-(qdiffsq / (2 * ls2)))'], {}), '(-(qdiffsq / (2 * ls2)))\n', (69313, 69337), False, 'from math import exp\n'), ((34209, 34230), 'math.exp', 'exp', (['(-r11 * r11 * ls1)'], {}), '(-r11 * r11 * ls1)\n', (34212, 34230), False, 'from math import exp\n'), ((51050, 51064), 'math.exp', 'exp', (['(-C6 * ls2)'], {}), '(-C6 * ls2)\n', (51053, 51064), False, 'from math import exp\n'), ((51033, 51047), 'math.exp', 'exp', (['(-C5 * ls2)'], {}), '(-C5 * ls2)\n', (51036, 51047), False, 'from math import exp\n'), ((50990, 51004), 'math.exp', 'exp', (['(-C4 * ls2)'], {}), '(-C4 * ls2)\n', (50993, 51004), False, 'from math import exp\n'), ((50973, 50987), 'math.exp', 'exp', (['(-C3 * ls2)'], {}), '(-C3 * ls2)\n', (50976, 50987), False, 'from math import exp\n'), ((50939, 50953), 'math.exp', 'exp', (['(-C1 * ls2)'], {}), '(-C1 * ls2)\n', (50942, 50953), False, 'from math import exp\n'), ((50956, 50970), 'math.exp', 'exp', (['(-C2 * ls2)'], {}), '(-C2 * ls2)\n', (50959, 50970), False, 'from math import exp\n')]
import numpy as np from numpy import allclose from hypothesis import given from hypothesis.strategies import integers, composite, lists from hypothesis.extra.numpy import arrays from fancy_einsum import einsum def tensor(draw, shape): return draw(arrays(dtype=int, shape=shape)) @composite def square_matrix(draw): n = draw(integers(2, 10)) return tensor(draw, (n, n)) @given(square_matrix()) def test_simple_matmul(mat): actual = einsum('length length ->', mat) assert allclose(actual, np.einsum('aa->', mat)) @composite def matmul_compatible(draw): b = draw(integers(1, 10)) r = draw(integers(1, 10)) t = draw(integers(1, 10)) c = draw(integers(1, 10)) return tensor(draw, (b, r, t)), tensor(draw, (b, t, c)) @given(matmul_compatible()) def test_ellipse_matmul(args): a, b = args actual = einsum('...rows temp, ...temp cols -> ...rows cols', a, b) assert allclose(actual, np.einsum('...rt,...tc->...rc', a, b)) @composite def chain_matmul(draw): sizes = [draw(integers(1, 4)) for _ in range(5)] shapes = [(sizes[i-1], sizes[i]) for i in range(1, len(sizes))] return [tensor(draw, shape) for shape in shapes] @given(chain_matmul()) def test_chain_matmul(args): actual = einsum('rows t1, t1 t2, t2 t3, t3 cols -> rows cols', *args) assert allclose(actual, np.einsum('ab,bc,cd,de->ae', *args))
[ "fancy_einsum.einsum", "hypothesis.strategies.integers", "numpy.einsum", "hypothesis.extra.numpy.arrays" ]
[((452, 483), 'fancy_einsum.einsum', 'einsum', (['"""length length ->"""', 'mat'], {}), "('length length ->', mat)\n", (458, 483), False, 'from fancy_einsum import einsum\n'), ((848, 906), 'fancy_einsum.einsum', 'einsum', (['"""...rows temp, ...temp cols -> ...rows cols"""', 'a', 'b'], {}), "('...rows temp, ...temp cols -> ...rows cols', a, b)\n", (854, 906), False, 'from fancy_einsum import einsum\n'), ((1252, 1312), 'fancy_einsum.einsum', 'einsum', (['"""rows t1, t1 t2, t2 t3, t3 cols -> rows cols"""', '*args'], {}), "('rows t1, t1 t2, t2 t3, t3 cols -> rows cols', *args)\n", (1258, 1312), False, 'from fancy_einsum import einsum\n'), ((253, 283), 'hypothesis.extra.numpy.arrays', 'arrays', ([], {'dtype': 'int', 'shape': 'shape'}), '(dtype=int, shape=shape)\n', (259, 283), False, 'from hypothesis.extra.numpy import arrays\n'), ((335, 350), 'hypothesis.strategies.integers', 'integers', (['(2)', '(10)'], {}), '(2, 10)\n', (343, 350), False, 'from hypothesis.strategies import integers, composite, lists\n'), ((512, 534), 'numpy.einsum', 'np.einsum', (['"""aa->"""', 'mat'], {}), "('aa->', mat)\n", (521, 534), True, 'import numpy as np\n'), ((591, 606), 'hypothesis.strategies.integers', 'integers', (['(1)', '(10)'], {}), '(1, 10)\n', (599, 606), False, 'from hypothesis.strategies import integers, composite, lists\n'), ((621, 636), 'hypothesis.strategies.integers', 'integers', (['(1)', '(10)'], {}), '(1, 10)\n', (629, 636), False, 'from hypothesis.strategies import integers, composite, lists\n'), ((651, 666), 'hypothesis.strategies.integers', 'integers', (['(1)', '(10)'], {}), '(1, 10)\n', (659, 666), False, 'from hypothesis.strategies import integers, composite, lists\n'), ((681, 696), 'hypothesis.strategies.integers', 'integers', (['(1)', '(10)'], {}), '(1, 10)\n', (689, 696), False, 'from hypothesis.strategies import integers, composite, lists\n'), ((935, 972), 'numpy.einsum', 'np.einsum', (['"""...rt,...tc->...rc"""', 'a', 'b'], {}), "('...rt,...tc->...rc', a, b)\n", (944, 972), True, 'import numpy as np\n'), ((1341, 1376), 'numpy.einsum', 'np.einsum', (['"""ab,bc,cd,de->ae"""', '*args'], {}), "('ab,bc,cd,de->ae', *args)\n", (1350, 1376), True, 'import numpy as np\n'), ((1029, 1043), 'hypothesis.strategies.integers', 'integers', (['(1)', '(4)'], {}), '(1, 4)\n', (1037, 1043), False, 'from hypothesis.strategies import integers, composite, lists\n')]
from collections import defaultdict import numpy as np import pandas as pd from easydict import EasyDict as edict import shapely.affinity from shapely import wkt import networkx as nx import aa.road_networks.wkt_to_graph def get_bigmap_chip_locations(aoi_name, fn_sub, df, aoi_data_path_mapping): cols = [ 'imname', 'ix', 'iy', 'ImageId', 'WKT_Pix', 'length_m', 'speed_mph', ] assert aoi_name in aoi_data_path_mapping.keys() df = df[(df.aoi_name == aoi_name) & (df['mode'] == 'test')] assert len(df) > 0 ix_min, ix_max, iy_min, iy_max = df['ix'].min(), df['ix'].max(), df['iy'].min(), df['iy'].max() df = df[(df['ix'] >= ix_min) & (df['ix'] <= ix_max) & (df['iy'] >= iy_min) & (df['iy'] <= iy_max)] df_sub = pd.read_csv(fn_sub).rename(columns={'inferred_speed_mph': 'speed_mph'}) df_sub = df_sub[df_sub.ImageId.str.startswith(aoi_name)].drop_duplicates() assert len(df_sub) > 0 df_sub.loc[:, 'imname'] = df_sub.ImageId.apply(lambda x: x.split('_')[-1]) df = df.merge(df_sub, how='left', on='imname') df = df.dropna(subset=['ImageId']) return edict(ix_min=ix_min, ix_max=ix_max, iy_min=iy_min, iy_max=iy_max), df def construct_graph_and_node_list(df): wkt_list = [] metadata_list = [] for _, r in df.iterrows(): wkt = shapely.affinity.translate( shapely.wkt.loads(r['WKT_Pix']), xoff=r['ix'] * 1300, yoff=r['iy'] * 1300).wkt if wkt == 'LINESTRING EMPTY': continue if wkt not in wkt_list: wkt_list.append(wkt) metadata_list.append(dict(WKT_Pix=r['WKT_Pix'], ImageId=r['ImageId'], imname=r['imname'], length_m=r['length_m'], speed_mph=r['speed_mph'], travel_time_s=r['travel_time_s'])) node_loc_dic, edge_dic = aa.road_networks.wkt_to_graph.wkt_list_to_nodes_edges(wkt_list) # xs, ys = shape.coords.xy G0 = aa.road_networks.wkt_to_graph.nodes_edges_to_G(node_loc_dic, edge_dic) for n, attr_dict in G0.nodes(data=True): x, y = attr_dict['x_pix'], attr_dict['y_pix'] attr_dict['x'] = x attr_dict['y'] = y * -1 # 9nvert top-bottom return metadata_list, node_loc_dic, edge_dic, G0 def make_chip_graph_connected(G0, node_loc_dic, ix_boundary_data, chip_connection_margin=20, distance_margin=40): df_merge = pd.DataFrame([ dict(node_id=node_id, x=x, y=y, x_in_chip=x%1300, y_in_chip=y%1300) for node_id, (x, y) in node_loc_dic.items() if ((x % 1300 < chip_connection_margin) or (y % 1300 < chip_connection_margin) or (x % 1300 >= (1300 - chip_connection_margin)) or (y % 1300 >= (1300 - chip_connection_margin))) and (len(G0[node_id]) > 0)]) df_merge.loc[:, 'ix'] = np.round((df_merge['x'] - df_merge['x'] % 1300) / 1300).astype(np.int32) df_merge.loc[:, 'iy'] = np.round((df_merge['y'] - df_merge['y'] % 1300) / 1300).astype(np.int32) G1 = G0.copy() ix_max = ix_boundary_data.ix_max ix_min = ix_boundary_data.ix_min iy_max = ix_boundary_data.iy_max iy_min = ix_boundary_data.iy_min for index_x in range(ix_max - ix_min + 1): stich_base_chip_ix = ix_min + index_x for index_y in range(iy_max - iy_min + 1): stich_base_chip_iy = iy_min + index_y if stich_base_chip_ix < ix_max: df_lhs = df_merge[(df_merge['iy'] == stich_base_chip_iy) & (df_merge['ix'] == stich_base_chip_ix)] df_rhs = df_merge[(df_merge['iy'] == stich_base_chip_iy) & (df_merge['ix'] == stich_base_chip_ix + 1)] for _, r in df_lhs[df_lhs.x_in_chip >= (1300 - chip_connection_margin)].iterrows(): for _, r2 in df_rhs[df_rhs.x_in_chip < chip_connection_margin].iterrows(): dist = abs(r.y_in_chip - r2.y_in_chip) if dist < distance_margin: G1.add_edge(r.node_id, r2.node_id, length_pix=0) if stich_base_chip_iy < iy_max: df_lhs = df_merge[(df_merge['iy'] == stich_base_chip_iy) & (df_merge['ix'] == stich_base_chip_ix)] df_rhs = df_merge[(df_merge['iy'] == stich_base_chip_iy + 1) & (df_merge['ix'] == stich_base_chip_ix)] for _, r in df_lhs[df_lhs.y_in_chip >= (1300 - chip_connection_margin)].iterrows(): for _, r2 in df_rhs[df_rhs.y_in_chip < chip_connection_margin].iterrows(): dist = abs(r.x_in_chip - r2.x_in_chip) if dist < distance_margin: G1.add_edge(r.node_id, r2.node_id, length_pix=0) return G1 def get_connected_component_dataframe(G1): connected_component = [] for i, cc in enumerate(nx.connected_component_subgraphs(G1)): edge_length_pix_ttl = 0 for src, dst in cc.edges(): edge_length_pix = sum([elem['length_pix'] for elem in cc[src][dst].values()]) edge_length_pix_ttl += edge_length_pix connected_component.append({'idx': i, 'edge_length_pix_total': edge_length_pix_ttl, 'cc': cc}) return pd.DataFrame(connected_component) def select_registered_nodes(df_cc, lowest_length_pix_connected_component, node_loc_dic): small_cc_nodes = set() for _, r in df_cc[df_cc.edge_length_pix_total > lowest_length_pix_connected_component].iterrows(): for v in r.cc.nodes(): small_cc_nodes.add(v) area_xmax, area_ymax = max([x for x, y in node_loc_dic.values()]), max([y for x, y in node_loc_dic.values()]) for _, r in df_cc.iterrows(): boundary_area_flag = False for v in r.cc.nodes(): x, y = node_loc_dic[v] if x < 650 or y < 650: boundary_area_flag = True break if x > area_xmax - 650 or y > area_ymax - 650: boundary_area_flag = True break if boundary_area_flag: for v in r.cc.nodes(): small_cc_nodes.add(v) return small_cc_nodes def make_refined_graph(fn_sub, edge_dic, selected_nodes, metadata_list, aoi_name): rows = [] for e in edge_dic: edge = edge_dic[e] if edge['start'] not in selected_nodes: continue if edge['end'] not in selected_nodes: continue idx = edge['osmid'] rows.append(dict( ImageId=metadata_list[idx]['ImageId'], WTK_Pix=metadata_list[idx]['WKT_Pix'], length_m=metadata_list[idx]['length_m'], travel_time_s=metadata_list[idx]['travel_time_s'], speed_mph=metadata_list[idx]['speed_mph'], )) df_rows_new = pd.DataFrame(rows).drop_duplicates() df_sub = pd.read_csv(fn_sub).rename(columns={'inferred_speed_mph': 'speed_mph'}) aoi_name_unique_image_ids = df_sub[df_sub.ImageId.str.startswith(aoi_name)].ImageId.unique() rows = [] empty_image_ids = [image_id for image_id in aoi_name_unique_image_ids if image_id not in df_rows_new.ImageId.unique()] for image_id in empty_image_ids: rows.append(dict( ImageId=image_id, WTK_Pix='LINESTRING EMPTY', length_m=0.0, travel_time_s=0.0, speed_mph=0.0, )) df_rows_new2 = pd.DataFrame(rows) df_sub_new = pd.concat([df_rows_new, df_rows_new2], sort=False).sort_values(by='ImageId') return df_sub_new def main(fn_sub, fn_out, fn_out_debug, df_chiplocations, aoi_data_path_mapping): list_df_sub = [] for aoi_name in sorted(aoi_data_path_mapping.keys()): lowest_length_pix_connected_component = 1000 ix_boundary_data, df = get_bigmap_chip_locations(aoi_name, fn_sub, df_chiplocations, aoi_data_path_mapping) metadata_list, node_loc_dic, edge_dic, G0 = construct_graph_and_node_list(df) G1 = make_chip_graph_connected(G0, node_loc_dic, ix_boundary_data, chip_connection_margin=20, distance_margin=40) df_cc = get_connected_component_dataframe(G1) selected_nodes = select_registered_nodes(df_cc, lowest_length_pix_connected_component, node_loc_dic) df_sub_refined = make_refined_graph(fn_sub, edge_dic, selected_nodes, metadata_list, aoi_name) G3 = G1 selected_remove_nodes = set() for idx, r in df_cc[df_cc.edge_length_pix_total > 1000].sort_values(by='edge_length_pix_total', ascending=False).iterrows(): is_simple_line = True degree_list = [] for node_id in r['cc']: degree_list.append(len(G3[node_id])) if np.mean(degree_list) > 2.001: is_simple_line = False if is_simple_line: cc_degree_set = defaultdict(set) for src in r['cc']: for dst in G3[src]: for e in G3[src][int(dst)].values(): if 'osmid' in e: pos = list(node_loc_dic[int(src)]) pos = list(node_loc_dic[int(dst)]) for node_loc in metadata_list[e['osmid']]['WKT_Pix'][12:-1].split(', '): node_loc = node_loc.split(' ') node_loc = (int(node_loc[0]), int(node_loc[1])) cc_degree_set[metadata_list[e['osmid']]['ImageId']].add(node_loc) neighbor_node_list = [] for imageid in cc_degree_set.keys(): for _, r2 in df[df['ImageId'] == imageid].iterrows(): for node_loc in r2['WKT_Pix'][12:-1].split(', '): node_loc = node_loc.split(' ') node_loc = (int(node_loc[0]), int(node_loc[1])) rhs_node_loc_set = cc_degree_set[imageid] if node_loc not in rhs_node_loc_set: for rhs_node_loc in rhs_node_loc_set: dist = np.sqrt((rhs_node_loc[0] - node_loc[0]) ** 2 + (rhs_node_loc[1] - node_loc[1]) ** 2) neighbor_node_list.append((dist, node_loc)) if len(neighbor_node_list) > 0: min_dist, _ = min(neighbor_node_list) if min_dist > 200: for node_id in list(r['cc']): selected_remove_nodes.add(node_id) print(min_dist, r['idx'], cc_degree_set.keys()) print([len(G3[node_id]) for node_id in r['cc']]) selected_nodes = [n for n in selected_nodes if n not in selected_remove_nodes] df_sub_refined = make_refined_graph(fn_sub, edge_dic, selected_nodes, metadata_list, aoi_name) list_df_sub.append(df_sub_refined) df_sub = pd.concat(list_df_sub, sort=False) df_sub[[ 'ImageId', 'WTK_Pix', 'length_m', 'travel_time_s', 'speed_mph', ]].rename(columns={'WTK_Pix': 'WKT_Pix'}).to_csv(fn_out_debug, index=False) df_sub[[ 'ImageId', 'WTK_Pix', 'length_m', 'travel_time_s', ]].rename(columns={'WTK_Pix': 'WKT_Pix'}).to_csv(fn_out, index=False) def main_stage2(fn_sub_stg2, fn_out_stg2, fn_out_debug_stg2, df_chiplocations, aoi_data_path_mapping): list_df_sub = [] for aoi_name in sorted(aoi_data_path_mapping.keys()): lowest_length_pix_connected_component = 10000 ix_boundary_data, df = get_bigmap_chip_locations(aoi_name, fn_sub_stg2, df_chiplocations, aoi_data_path_mapping) metadata_list, node_loc_dic, edge_dic, G0 = construct_graph_and_node_list(df) G1 = make_chip_graph_connected(G0, node_loc_dic, ix_boundary_data, chip_connection_margin=20, distance_margin=40) df_cc = get_connected_component_dataframe(G1) selected_nodes = select_registered_nodes(df_cc, lowest_length_pix_connected_component, node_loc_dic) df_sub_refined = make_refined_graph(fn_sub_stg2, edge_dic, selected_nodes, metadata_list, aoi_name) list_df_sub.append(df_sub_refined) df_sub = pd.concat(list_df_sub, sort=False) df_sub[[ 'ImageId', 'WTK_Pix', 'length_m', 'travel_time_s', 'speed_mph', ]].rename(columns={'WTK_Pix': 'WKT_Pix'}).to_csv(fn_out_debug_stg2, index=False) df_sub[[ 'ImageId', 'WTK_Pix', 'length_m', 'travel_time_s', ]].rename(columns={'WTK_Pix': 'WKT_Pix'}).to_csv(fn_out_stg2, index=False)
[ "pandas.DataFrame", "pandas.read_csv", "collections.defaultdict", "numpy.mean", "easydict.EasyDict", "networkx.connected_component_subgraphs", "numpy.round", "pandas.concat", "numpy.sqrt" ]
[((5476, 5509), 'pandas.DataFrame', 'pd.DataFrame', (['connected_component'], {}), '(connected_component)\n', (5488, 5509), True, 'import pandas as pd\n'), ((7646, 7664), 'pandas.DataFrame', 'pd.DataFrame', (['rows'], {}), '(rows)\n', (7658, 7664), True, 'import pandas as pd\n'), ((11425, 11459), 'pandas.concat', 'pd.concat', (['list_df_sub'], {'sort': '(False)'}), '(list_df_sub, sort=False)\n', (11434, 11459), True, 'import pandas as pd\n'), ((13227, 13261), 'pandas.concat', 'pd.concat', (['list_df_sub'], {'sort': '(False)'}), '(list_df_sub, sort=False)\n', (13236, 13261), True, 'import pandas as pd\n'), ((1204, 1269), 'easydict.EasyDict', 'edict', ([], {'ix_min': 'ix_min', 'ix_max': 'ix_max', 'iy_min': 'iy_min', 'iy_max': 'iy_max'}), '(ix_min=ix_min, ix_max=ix_max, iy_min=iy_min, iy_max=iy_max)\n', (1209, 1269), True, 'from easydict import EasyDict as edict\n'), ((5114, 5150), 'networkx.connected_component_subgraphs', 'nx.connected_component_subgraphs', (['G1'], {}), '(G1)\n', (5146, 5150), True, 'import networkx as nx\n'), ((843, 862), 'pandas.read_csv', 'pd.read_csv', (['fn_sub'], {}), '(fn_sub)\n', (854, 862), True, 'import pandas as pd\n'), ((3131, 3186), 'numpy.round', 'np.round', (["((df_merge['x'] - df_merge['x'] % 1300) / 1300)"], {}), "((df_merge['x'] - df_merge['x'] % 1300) / 1300)\n", (3139, 3186), True, 'import numpy as np\n'), ((3232, 3287), 'numpy.round', 'np.round', (["((df_merge['y'] - df_merge['y'] % 1300) / 1300)"], {}), "((df_merge['y'] - df_merge['y'] % 1300) / 1300)\n", (3240, 3287), True, 'import numpy as np\n'), ((7041, 7059), 'pandas.DataFrame', 'pd.DataFrame', (['rows'], {}), '(rows)\n', (7053, 7059), True, 'import pandas as pd\n'), ((7092, 7111), 'pandas.read_csv', 'pd.read_csv', (['fn_sub'], {}), '(fn_sub)\n', (7103, 7111), True, 'import pandas as pd\n'), ((7683, 7733), 'pandas.concat', 'pd.concat', (['[df_rows_new, df_rows_new2]'], {'sort': '(False)'}), '([df_rows_new, df_rows_new2], sort=False)\n', (7692, 7733), True, 'import pandas as pd\n'), ((9101, 9121), 'numpy.mean', 'np.mean', (['degree_list'], {}), '(degree_list)\n', (9108, 9121), True, 'import numpy as np\n'), ((9234, 9250), 'collections.defaultdict', 'defaultdict', (['set'], {}), '(set)\n', (9245, 9250), False, 'from collections import defaultdict\n'), ((10551, 10640), 'numpy.sqrt', 'np.sqrt', (['((rhs_node_loc[0] - node_loc[0]) ** 2 + (rhs_node_loc[1] - node_loc[1]) ** 2)'], {}), '((rhs_node_loc[0] - node_loc[0]) ** 2 + (rhs_node_loc[1] - node_loc[\n 1]) ** 2)\n', (10558, 10640), True, 'import numpy as np\n')]
""" basic functions needed to train and test deep learning models with PyTorch """ import torch import numpy as np import sys def make_fake_side_info(voice_spectro_tensor): voice_energy = torch.sum(voice_spectro_tensor, dim=2, keepdim=True) fake_side_info = torch.ones_like(voice_energy) return fake_side_info def viterbi_alignment_from_attention(attention_weights, hop_len): """ :param attention_weights: shape (M, N) :param hop_len: int :return: """ M = attention_weights.shape[0] N = attention_weights.shape[1] # transition probabilities are zero everywhere except when going back to the same state (m --> m) # or moving to next state (m --> m+1). First dimension (vertical) is the starting state, # second dimension (horizontally) is the arriving state # initialize transition probabilities to 0.5 for both allowed cases trans_p = np.zeros((M, M)) for m in range(M): trans_p[m, m] = 0.5 if m < M - 1: trans_p[m, m+1] = 0.5 # initialization delta = np.zeros((M, N)) # shape: (states, time_steps), contains delta_n(m) delta[0, 0] = 1 # delta_0(0) = 1 first state (silence token) must be active at first time step psi = np.zeros((M, N)) # state that is most likely predecessor of state m at time step n # recurrence for n in range(1, N): for m in range(M): delta_m_n_candidates = [] for m_candidate in range(M): delta_m_n_candidates.append(delta[m_candidate, n-1] * trans_p[m_candidate, m]) delta[m, n] = max(delta_m_n_candidates) * (attention_weights[m, n] * 2 + 1) psi[m, n] = np.argmax(delta_m_n_candidates) np.set_printoptions(threshold=sys.maxsize) optimal_state_sequence = np.zeros((1, N)) optimal_state_sequence[0, N-1] = int(M - 1) # force the last state (silent token) to be active at last time step for n in range(N-2, 0, -1): optimal_state_sequence[0, n] = (psi[int(optimal_state_sequence[0, n+1]), n+1]) # compute index of list elements whose right neighbor is different from itself last_idx_before_change = [i for i, (x, y) in enumerate(zip(optimal_state_sequence[0, :-1], optimal_state_sequence[0, 1:])) if x != y] # compute phoneme onset times from idx of last time frame previous phoneme phoneme_onsets_prediction = [(n + 1) * hop_len / 16000 for n in last_idx_before_change] phoneme_onsets_prediction = phoneme_onsets_prediction[:-1] # remove onset prediction of silence token # the optimal_state_sequence is a sequence of phoneme indices with length N return optimal_state_sequence.astype(int), phoneme_onsets_prediction def train_with_attention(model, loss_function, optimizer, mix_inputs, side_info, targets): model.train() optimizer.zero_grad() # Forward output_of_network, _ = model(mix_inputs, side_info) loss = loss_function(output_of_network, targets) # Backward loss.backward() # Update parameters optimizer.step() # return a number that represents the loss return loss.item() def train_with_perfect_attention(model, loss_function, optimizer, mix_inputs, side_info, targets, alphas): model.train() optimizer.zero_grad() # Forward output_of_network, _ = model(mix_inputs, side_info, alphas) loss = loss_function(output_of_network, targets) # Backward loss.backward() # Update parameters optimizer.step() # return a number that represents the loss return loss.item() def predict_with_attention(model, mix_input, side_info): model.eval() prediction, alphas = model(mix_input, side_info) return prediction, alphas def predict_with_perfect_attention(model, mix_input, side_info, alphas_in): model.eval() prediction, alphas = model(mix_input, side_info, alphas_in) return prediction, alphas def eval_source_separation_silent_parts(true_source, predicted_source, window_size, hop_size): num_eval_windows = int(np.ceil((len(true_source) - abs(hop_size - window_size)) / hop_size)) -1 list_prediction_energy_at_true_silence = [] list_true_energy_at_predicted_silence = [] for ii in range(num_eval_windows): prediction_window = predicted_source[ii * window_size: ii * window_size + window_size] true_window = true_source[ii * window_size: ii * window_size + window_size] # compute predicted energy for silent true source (PESTS) if sum(abs(true_window)) == 0: prediction_energy_at_true_silence = 10 * np.log10(sum(prediction_window**2) + 10**(-12)) list_prediction_energy_at_true_silence.append(prediction_energy_at_true_silence) else: # list_prediction_energy_at_true_silence.append(np.nan) pass # compute energy of true source when silence (all zeros) is predicted and true source is not silent// # True Energy at Wrong Silence Prediction (TEWSP) if sum(abs(prediction_window)) == 0 and sum(abs(true_window)) != 0: true_source_energy_at_silent_prediction = 10 * np.log10(sum(true_window**2) + 10**(-12)) list_true_energy_at_predicted_silence.append(true_source_energy_at_silent_prediction) else: # list_true_energy_at_predicted_silence.append(np.nan) pass return np.asarray(list_prediction_energy_at_true_silence), np.asarray(list_true_energy_at_predicted_silence)
[ "torch.ones_like", "numpy.set_printoptions", "numpy.argmax", "numpy.asarray", "numpy.zeros", "torch.sum" ]
[((194, 246), 'torch.sum', 'torch.sum', (['voice_spectro_tensor'], {'dim': '(2)', 'keepdim': '(True)'}), '(voice_spectro_tensor, dim=2, keepdim=True)\n', (203, 246), False, 'import torch\n'), ((269, 298), 'torch.ones_like', 'torch.ones_like', (['voice_energy'], {}), '(voice_energy)\n', (284, 298), False, 'import torch\n'), ((905, 921), 'numpy.zeros', 'np.zeros', (['(M, M)'], {}), '((M, M))\n', (913, 921), True, 'import numpy as np\n'), ((1063, 1079), 'numpy.zeros', 'np.zeros', (['(M, N)'], {}), '((M, N))\n', (1071, 1079), True, 'import numpy as np\n'), ((1243, 1259), 'numpy.zeros', 'np.zeros', (['(M, N)'], {}), '((M, N))\n', (1251, 1259), True, 'import numpy as np\n'), ((1724, 1766), 'numpy.set_printoptions', 'np.set_printoptions', ([], {'threshold': 'sys.maxsize'}), '(threshold=sys.maxsize)\n', (1743, 1766), True, 'import numpy as np\n'), ((1797, 1813), 'numpy.zeros', 'np.zeros', (['(1, N)'], {}), '((1, N))\n', (1805, 1813), True, 'import numpy as np\n'), ((5380, 5430), 'numpy.asarray', 'np.asarray', (['list_prediction_energy_at_true_silence'], {}), '(list_prediction_energy_at_true_silence)\n', (5390, 5430), True, 'import numpy as np\n'), ((5432, 5481), 'numpy.asarray', 'np.asarray', (['list_true_energy_at_predicted_silence'], {}), '(list_true_energy_at_predicted_silence)\n', (5442, 5481), True, 'import numpy as np\n'), ((1687, 1718), 'numpy.argmax', 'np.argmax', (['delta_m_n_candidates'], {}), '(delta_m_n_candidates)\n', (1696, 1718), True, 'import numpy as np\n')]
# -------------- import numpy as np data=np.genfromtxt(path,delimiter=",", skip_header=1) new_record=[[50,9,4,1,0,0,40,0]] census=np.concatenate([data,new_record],axis=0) # -------------- import numpy as np age=np.array(census[0:,0]) max_age=np.max(age) min_age=np.min(age) age_mean=age.mean() age_std=np.std(age) # -------------- import numpy as np race_0=census[census[:,2]==0] race_1=census[census[:,2]==1] race_2=census[census[:,2]==2] race_3=census[census[:,2]==3] race_4=census[census[:,2]==4] len_0=len(race_0) len_1=len(race_1) len_2=len(race_2) len_3=len(race_3) len_4=len(race_4) race_list=[len_0,len_1,len_2,len_3,len_4] minority_race=race_list.index(min(race_list)) # -------------- import numpy as np k=census[:,0] senior_citizens=census[k>60] working_hours_sum=senior_citizens.sum(axis=0)[6] senior_citizens_len=len(senior_citizens) avg_working_hours=working_hours_sum/senior_citizens_len print(avg_working_hours) # -------------- import numpy as np p=census[:,1] high=census[p>10] low=census[p<=10] avg_pay_high=high.mean(axis=0)[7] avg_pay_low=low.mean(axis=0)[7] np.array_equal(avg_pay_high,avg_pay_low)
[ "numpy.std", "numpy.genfromtxt", "numpy.max", "numpy.min", "numpy.array", "numpy.array_equal", "numpy.concatenate" ]
[((42, 91), 'numpy.genfromtxt', 'np.genfromtxt', (['path'], {'delimiter': '""","""', 'skip_header': '(1)'}), "(path, delimiter=',', skip_header=1)\n", (55, 91), True, 'import numpy as np\n'), ((133, 175), 'numpy.concatenate', 'np.concatenate', (['[data, new_record]'], {'axis': '(0)'}), '([data, new_record], axis=0)\n', (147, 175), True, 'import numpy as np\n'), ((217, 240), 'numpy.array', 'np.array', (['census[0:, 0]'], {}), '(census[0:, 0])\n', (225, 240), True, 'import numpy as np\n'), ((249, 260), 'numpy.max', 'np.max', (['age'], {}), '(age)\n', (255, 260), True, 'import numpy as np\n'), ((270, 281), 'numpy.min', 'np.min', (['age'], {}), '(age)\n', (276, 281), True, 'import numpy as np\n'), ((312, 323), 'numpy.std', 'np.std', (['age'], {}), '(age)\n', (318, 323), True, 'import numpy as np\n'), ((1120, 1161), 'numpy.array_equal', 'np.array_equal', (['avg_pay_high', 'avg_pay_low'], {}), '(avg_pay_high, avg_pay_low)\n', (1134, 1161), True, 'import numpy as np\n')]
from abc import ABC, abstractmethod from collections import defaultdict import numpy as np import torch from utils.additional import storage_saver class GAE: """ Generalized Advantage Estimator. See [Schulman et al., 2016](https://arxiv.org/abs/1506.02438) """ def __init__(self, policy, gamma=0.99, lambda_=0.95, normalize=None, epsilon=1e-8): self.policy = policy self.gamma = gamma self.lambda_ = lambda_ self.normalize = normalize self.epsilon = epsilon def __call__(self, trajectory): """ Applies the advantage estimator to a given trajectory. Returns: a tuple of (advantages, value_targets). """ if "advantages" in trajectory: raise ValueError("trajectory cannot contain 'advantages'") if "value_targets" in trajectory: raise ValueError("trajectory cannot contain 'value_targets'") rewards = trajectory["rewards"] resets = trajectory["resets"] values = trajectory["values"] # Values might have an additional last dimension of size 1 as outputs of # dense layers. Need to adjust shapes of rewards and resets accordingly. if (not (0 <= values.ndim - rewards.ndim <= 1) or values.ndim == rewards.ndim + 1 and values.shape[-1] != 1): raise ValueError( f"trajectory['values'] of shape {trajectory['values'].shape} " "must have the same number of dimensions as " f"trajectory['rewards'] which has shape {rewards.shape} " "or have last dimension of size 1") if values.ndim == rewards.ndim + 1: values = np.squeeze(values, -1) gae = np.zeros_like(values, dtype=np.float32) gae[-1] = rewards[-1] - values[-1] observation = trajectory["state"]["latest_observation"] state = trajectory["state"].get("policy_state", None) last_value = self.policy.act(observation, state=state, update_state=False)["values"] if np.asarray(resets[-1]).ndim < last_value.ndim: last_value = np.squeeze(last_value, -1) gae[-1] += (1 - resets[-1]) * self.gamma * last_value for i in range(gae.shape[0] - 1, 0, -1): not_reset = 1 - resets[i - 1] next_values = values[i] delta = (rewards[i - 1] + not_reset * self.gamma * next_values - values[i - 1]) gae[i - 1] = delta + not_reset * self.gamma * self.lambda_ * gae[i] value_targets = gae + values value_targets = value_targets[ (...,) + (None,) * (trajectory["values"].ndim - value_targets.ndim)] if self.normalize or self.normalize is None and gae.size > 1: gae = (gae - gae.mean()) / (gae.std() + self.epsilon) trajectory["advantages"] = gae trajectory["value_targets"] = value_targets return gae, value_targets class BaseRunner1(ABC): """ General data runner. """ def __init__(self, env, policy, step_var=None): self.env = env self.policy = policy if step_var is None: step_var = torch.zeros(1, requires_grad=False) self.step_var = step_var @property def nenvs(self): """ Returns number of batched envs or `None` if env is not batched """ return getattr(self.env.unwrapped, "nenvs", None) @abstractmethod def get_next(self): """ Returns next data object """ class BaseRunnerNoController(ABC): """ General data runner. """ def __init__(self, env, step_var=None): self.env = env if step_var is None: step_var = torch.zeros(1, requires_grad=False) self.step_var = step_var @property def nenvs(self): """ Returns number of batched envs or `None` if env is not batched """ return getattr(self.env.unwrapped, "nenvs", None) @abstractmethod def get_next(self): """ Returns next data object """ class EnvRunnerNoController(BaseRunnerNoController): # pylint: disable=too-many-arguments def __init__(self, env, nsteps, cutoff=None, asarray=True, transforms=None, step_var=None): super().__init__(env, step_var) self.env = env self.nsteps = nsteps self.cutoff = cutoff self.asarray = asarray self.transforms = transforms or [] self.state = {"latest_observation": self.env.reset()} def reset(self, policy=None): """ Resets env and runner states. """ self.state["latest_observation"] = self.env.reset() if policy: policy.reset() def get_next(self, act, observations, rewards, resets, trajectory): """ Runs the agent in the environment. """ observations.append(self.state["latest_observation"]) if "actions" not in act: raise ValueError(f"result of policy.act must contain 'actions' but has keys {list(act.keys())}") for key, val in act.items(): if isinstance(trajectory[key], list): trajectory[key].append(val) if isinstance(trajectory[key], np.ndarray): trajectory[key] = trajectory[key].tolist() trajectory[key].append(val) architecture = trajectory["actions"][-1] storage_saver.set_architecture(architecture) obs, rew, done, _ = self.env.step(architecture) self.state["latest_observation"] = obs rewards.append(rew) resets.append(done) # self.step_var.assign_add(self.nenvs or 1) if self.nenvs is not None and self.nenvs > 1: self.step_var += self.nenvs else: self.step_var += 1 # Only reset if the env is not batched. Batched envs should auto-reset. if not self.nenvs and np.all(done): self.state["env_steps"] = 1 self.state["latest_observation"] = self.env.reset() trajectory.update(observations=observations, rewards=rewards, resets=resets) if self.asarray: for key, val in trajectory.items(): try: trajectory[key] = np.asarray(val) except ValueError: raise ValueError(f"cannot convert value under key '{key}' to np.ndarray") trajectory["state"] = self.state for transform in self.transforms: transform(trajectory) return trajectory class EnvRunner1(BaseRunner1): # pylint: disable=too-many-arguments def __init__(self, env, policy, nsteps, cutoff=None, asarray=True, transforms=None, step_var=None): super().__init__(env, policy, step_var) self.env = env self.policy = policy self.nsteps = nsteps self.cutoff = cutoff self.asarray = asarray self.transforms = transforms or [] self.state = {"latest_observation": self.env.reset()} def reset(self): """ Resets env and runner states. """ self.state["latest_observation"] = self.env.reset() self.policy.reset() def get_next(self): """ Runs the agent in the environment. """ trajectory = defaultdict(list, {"actions": []}) observations = [] rewards = [] resets = [] self.state["env_steps"] = self.nsteps if self.policy.is_recurrent(): self.state["policy_state"] = self.policy.get_state() for i in range(self.nsteps): observations.append(self.state["latest_observation"]) act = self.policy.act(self.state["latest_observation"]) if "actions" not in act: raise ValueError(f"result of policy.act must contain 'actions' but has keys {list(act.keys())}") for key, val in act.items(): trajectory[key].append(val) obs, rew, done, _ = self.env.step(trajectory["actions"][-1]) self.state["latest_observation"] = obs rewards.append(rew) resets.append(done) if self.nenvs is not None and self.nenvs > 1: self.step_var += self.nenvs else: self.step_var += 1 # Only reset if the env is not batched. Batched envs should auto-reset. if not self.nenvs and np.all(done): self.state["env_steps"] = i + 1 self.state["latest_observation"] = self.env.reset() if self.cutoff or (self.cutoff is None and self.policy.is_recurrent()): break trajectory.update(observations=observations, rewards=rewards, resets=resets) if self.asarray: for key, val in trajectory.items(): try: trajectory[key] = np.asarray(val) except ValueError: raise ValueError(f"cannot convert value under key '{key}' to np.ndarray") trajectory["state"] = self.state for transform in self.transforms: transform(trajectory) return trajectory class TrajectorySampler(BaseRunner1): """ Samples parts of trajectory for specified number of epochs. """ # pylint: disable=too-many-instance-attributes def __init__(self, runner, num_epochs=4, num_minibatches=4, shuffle_before_epoch=True, transforms=None): super().__init__(runner.env, runner.policy, runner.step_var) self.runner = runner self.num_epochs = num_epochs self.num_minibatches = num_minibatches self.shuffle_before_epoch = shuffle_before_epoch self.transforms = transforms or [] self.minibatch_count = 0 self.epoch_count = 0 self.trajectory = None def trajectory_is_stale(self): """ True iff new trajectory should be generated for sub-sampling. """ return self.epoch_count >= self.num_epochs def shuffle_trajectory(self): """ Reshuffles trajectory along the first dimension. """ sample_size = self.trajectory["observations"].shape[0] indices = np.random.permutation(sample_size) for key, val in filter(lambda kv: isinstance(kv[1], np.ndarray), self.trajectory.items()): self.trajectory[key] = val[indices] def get_next(self): if self.trajectory is None or self.trajectory_is_stale(): self.epoch_count = self.minibatch_count = 0 self.trajectory = self.runner.get_next() if self.shuffle_before_epoch: self.shuffle_trajectory() sample_size = self.trajectory["observations"].shape[0] mbsize = sample_size // self.num_minibatches start = self.minibatch_count * mbsize indices = np.arange(start, min(start + mbsize, sample_size)) minibatch = {key: val[indices] for key, val in self.trajectory.items() if isinstance(val, np.ndarray)} self.minibatch_count += 1 if self.minibatch_count == self.num_minibatches: self.minibatch_count = 0 self.epoch_count += 1 if self.shuffle_before_epoch and not self.trajectory_is_stale(): self.shuffle_trajectory() for transform in self.transforms: transform(minibatch) return minibatch class SavedRewardsResetsRunner(BaseRunner1): """ Saves rewards and resets to an internall collection. """ def __init__(self, runner): if isinstance(runner, TrajectorySampler): unwrapped_runner = runner.runner else: unwrapped_runner = runner assert isinstance(unwrapped_runner, EnvRunner1) super().__init__(runner.env, runner.policy, step_var=runner.step_var) self.runner = runner self.rewards = [] self.resets = [] true_get_next = unwrapped_runner.get_next def wrapped_get_next(): trajectory = true_get_next() self.rewards.append(trajectory["rewards"]) self.resets.append(trajectory["resets"]) return trajectory unwrapped_runner.get_next = wrapped_get_next def get_next(self): return self.runner.get_next() def get_rewards_resets(self): """ Returns tuple of (rewards, resets) """ return np.concatenate(self.rewards, 0), np.concatenate(self.resets, 0) def clear_rewards_resets(self): """ Clears underlying collections of rewards and resets. """ self.rewards.clear() self.resets.clear() def __getattr__(self, attr): return getattr(self.runner, attr) class MergeTimeBatch: """ Merges first two axes typically representing time and env batch. """ def __call__(self, trajectory): assert trajectory["resets"].ndim == 2, trajectory["resets"].shape for key, val in filter(lambda kv: isinstance(kv[1], np.ndarray), trajectory.items()): trajectory[key] = np.reshape(val, (-1, *val.shape[2:])) class NormalizeAdvantages: """ Normalizes advantages. """ def __init__(self, epsilon=1e-8): self.epsilon = epsilon def __call__(self, trajectory): advantages = trajectory["advantages"] trajectory["advantages"] = ((advantages - advantages.mean()) / (advantages.std() + self.epsilon)) def make_ppo_runner(env, policy, num_runner_steps, gamma=0.99, lambda_=0.95, num_epochs=3, num_minibatches=4): """ Returns env runner for PPO """ transforms = [GAE(policy, gamma=gamma, lambda_=lambda_, normalize=False)] if not policy.is_recurrent() and getattr(env.unwrapped, "nenvs", None): transforms.append(MergeTimeBatch()) runner = EnvRunner1(env, policy, num_runner_steps, transforms=transforms) runner = TrajectorySampler(runner, num_epochs=num_epochs, num_minibatches=num_minibatches, transforms=[NormalizeAdvantages()]) return runner
[ "numpy.zeros_like", "utils.additional.storage_saver.set_architecture", "numpy.concatenate", "numpy.asarray", "torch.zeros", "collections.defaultdict", "numpy.reshape", "numpy.random.permutation", "numpy.squeeze", "numpy.all" ]
[((1759, 1798), 'numpy.zeros_like', 'np.zeros_like', (['values'], {'dtype': 'np.float32'}), '(values, dtype=np.float32)\n', (1772, 1798), True, 'import numpy as np\n'), ((5407, 5451), 'utils.additional.storage_saver.set_architecture', 'storage_saver.set_architecture', (['architecture'], {}), '(architecture)\n', (5437, 5451), False, 'from utils.additional import storage_saver\n'), ((7266, 7300), 'collections.defaultdict', 'defaultdict', (['list', "{'actions': []}"], {}), "(list, {'actions': []})\n", (7277, 7300), False, 'from collections import defaultdict\n'), ((10149, 10183), 'numpy.random.permutation', 'np.random.permutation', (['sample_size'], {}), '(sample_size)\n', (10170, 10183), True, 'import numpy as np\n'), ((1721, 1743), 'numpy.squeeze', 'np.squeeze', (['values', '(-1)'], {}), '(values, -1)\n', (1731, 1743), True, 'import numpy as np\n'), ((2181, 2207), 'numpy.squeeze', 'np.squeeze', (['last_value', '(-1)'], {}), '(last_value, -1)\n', (2191, 2207), True, 'import numpy as np\n'), ((3248, 3283), 'torch.zeros', 'torch.zeros', (['(1)'], {'requires_grad': '(False)'}), '(1, requires_grad=False)\n', (3259, 3283), False, 'import torch\n'), ((3766, 3801), 'torch.zeros', 'torch.zeros', (['(1)'], {'requires_grad': '(False)'}), '(1, requires_grad=False)\n', (3777, 3801), False, 'import torch\n'), ((5913, 5925), 'numpy.all', 'np.all', (['done'], {}), '(done)\n', (5919, 5925), True, 'import numpy as np\n'), ((12381, 12412), 'numpy.concatenate', 'np.concatenate', (['self.rewards', '(0)'], {}), '(self.rewards, 0)\n', (12395, 12412), True, 'import numpy as np\n'), ((12414, 12444), 'numpy.concatenate', 'np.concatenate', (['self.resets', '(0)'], {}), '(self.resets, 0)\n', (12428, 12444), True, 'import numpy as np\n'), ((13051, 13088), 'numpy.reshape', 'np.reshape', (['val', '(-1, *val.shape[2:])'], {}), '(val, (-1, *val.shape[2:]))\n', (13061, 13088), True, 'import numpy as np\n'), ((2109, 2131), 'numpy.asarray', 'np.asarray', (['resets[-1]'], {}), '(resets[-1])\n', (2119, 2131), True, 'import numpy as np\n'), ((8387, 8399), 'numpy.all', 'np.all', (['done'], {}), '(done)\n', (8393, 8399), True, 'import numpy as np\n'), ((6250, 6265), 'numpy.asarray', 'np.asarray', (['val'], {}), '(val)\n', (6260, 6265), True, 'import numpy as np\n'), ((8849, 8864), 'numpy.asarray', 'np.asarray', (['val'], {}), '(val)\n', (8859, 8864), True, 'import numpy as np\n')]
# -*- coding=utf-8 -*- import numpy as np import random import gzip import pickle def sigmoid(z): """The sigmoid function.""" return 1.0/(1.0+np.exp(-z)) def sigmoid_prime(z): """Derivative of the sigmoid function.""" return sigmoid(z)*(1-sigmoid(z)) def vectorized_result(j): """Return a 10-dimensional unit vector with a 1.0 in the jth position and zeroes elsewhere. This is used to convert a digit (0...9) into a corresponding desired output from the neural network.""" e = np.zeros((10, 1)) e[j] = 1.0 return e class Netwrk(object): """ neural network gradient descent """ def __init__(self, sizes): self.sizes = len(sizes) # 神经网络有几层 self.num_layers = len(sizes) self.biases = [np.random.randn(y,1)for y in sizes[1:]] self.weights = [np.random.randn(y, x) for x, y in zip(sizes[:-1], sizes[1:])] def feedforward(self, a): """Return the output of the network if ``a`` is input.""" for b, w in zip(self.biases, self.weights): a = sigmoid(np.dot(w, a)+b) return a def SGD(self,training_data, epochs, mini_batch_size, eta, test_data=None): """ stochastic gradient descent epochs: 训练多少轮 mini_batch_size: 每一个sample包含多少个实例 eta: 学习率 """ if test_data: n_test = len(test_data) n = len(training_data) for j in range(epochs): random.shuffle(training_data) # 对训练集数据进行乱序(重新洗牌) mini_batchs = [training_data[k:k+mini_batch_size] for k in range(0, n, mini_batch_size)] # 以mini_batch_size = 10 为例: # mini_bachs = [[0,1,2...,9], [10, ..., 19], [20,...,29], ....] for mini_batch in mini_batchs: self.update_mini_batch(mini_batch, eta) if test_data: print("Epoch {0} : {1} / {2}".format(j, self.evaluate(test_data), n_test)) else: print("Epoch {0} complete.".format(j)) def update_mini_batch(self, mini_batch, eta): """ update the network's weight and biases by applying gradient descent using backpropagation """ nabla_b = [np.zeros(b.shape) for b in self.biases] nabla_w = [np.zeros(w.shape) for w in self.weights] for x, y in mini_batch: delta_nabla_b, delta_nabla_w = self.backprop(x, y) nabla_b = [x+y for x,y in zip(nabla_b, delta_nabla_b)] nabla_w = [x+y for x,y in zip(nabla_w, delta_nabla_w)] m = len(mini_batch) self.weights = [w1 - (eta/m)*w2 for w1 , w2 in zip(self.weights, nabla_w)] self.biases = [b1 - (eta/m)*b2 for b1, b2 in zip(self.biases, nabla_b)] def backprop(self, x, y): """Return a tuple ``(nabla_b, nabla_w)`` representing the gradient for the cost function C_x. ``nabla_b`` and ``nabla_w`` are layer-by-layer lists of numpy arrays, similar to ``self.biases`` and ``self.weights``.""" nabla_b = [np.zeros(b.shape) for b in self.biases] nabla_w = [np.zeros(w.shape) for w in self.weights] # feedforward activation = x activations = [x] # list to store all the activations, layer by layer zs = [] # list to store all the z vectors, layer by layer for b, w in zip(self.biases, self.weights): z = np.dot(w, activation)+b zs.append(z) activation = sigmoid(z) activations.append(activation) # backward pass delta = self.cost_derivative(activations[-1], y) * \ sigmoid_prime(zs[-1]) nabla_b[-1] = delta nabla_w[-1] = np.dot(delta, activations[-2].transpose()) # Note that the variable l in the loop below is used a little # differently to the notation in Chapter 2 of the book. Here, # l = 1 means the last layer of neurons, l = 2 is the # second-last layer, and so on. It's a renumbering of the # scheme in the book, used here to take advantage of the fact # that Python can use negative indices in lists. for l in range(2, self.num_layers): z = zs[-l] sp = sigmoid_prime(z) delta = np.dot(self.weights[-l+1].transpose(), delta) * sp nabla_b[-l] = delta nabla_w[-l] = np.dot(delta, activations[-l-1].transpose()) return (nabla_b, nabla_w) def evaluate(self, test_data): """Return the number of test inputs for which the neural network outputs the correct result. Note that the neural network's output is assumed to be the index of whichever neuron in the final layer has the highest activation.""" test_results = [(np.argmax(self.feedforward(x)), y) for (x, y) in test_data] return sum(int(x == y) for (x, y) in test_results) def cost_derivative(self, output_activations, y): """Return the vector of partial derivatives \partial C_x / \partial a for the output activations.""" return (output_activations-y) def mnist_data_load(): with gzip.open('./neural-networks-and-deep-learning/data/mnist.pkl.gz', 'rb') as f: tr_d, va_d, te_d = pickle.load(f, encoding='bytes') # tr_d, va_d, te_d = load_data() training_inputs = [np.reshape(x, (784, 1)) for x in tr_d[0]] training_results = [vectorized_result(y) for y in tr_d[1]] training_data = zip(training_inputs, training_results) validation_inputs = [np.reshape(x, (784, 1)) for x in va_d[0]] validation_data = zip(validation_inputs, va_d[1]) test_inputs = [np.reshape(x, (784, 1)) for x in te_d[0]] test_data = zip(test_inputs, te_d[1]) return (training_data, validation_data, test_data) if __name__ == "__main__": net = Netwrk([784,30,10]) training_data, validation_data, test_data = mnist_data_load() net.SGD(training_data=list(training_data), epochs=100, mini_batch_size=100, eta=0.5, test_data=list(test_data))
[ "gzip.open", "numpy.random.randn", "random.shuffle", "numpy.zeros", "pickle.load", "numpy.exp", "numpy.reshape", "numpy.dot" ]
[((520, 537), 'numpy.zeros', 'np.zeros', (['(10, 1)'], {}), '((10, 1))\n', (528, 537), True, 'import numpy as np\n'), ((5145, 5217), 'gzip.open', 'gzip.open', (['"""./neural-networks-and-deep-learning/data/mnist.pkl.gz"""', '"""rb"""'], {}), "('./neural-networks-and-deep-learning/data/mnist.pkl.gz', 'rb')\n", (5154, 5217), False, 'import gzip\n'), ((5251, 5283), 'pickle.load', 'pickle.load', (['f'], {'encoding': '"""bytes"""'}), "(f, encoding='bytes')\n", (5262, 5283), False, 'import pickle\n'), ((5348, 5371), 'numpy.reshape', 'np.reshape', (['x', '(784, 1)'], {}), '(x, (784, 1))\n', (5358, 5371), True, 'import numpy as np\n'), ((5537, 5560), 'numpy.reshape', 'np.reshape', (['x', '(784, 1)'], {}), '(x, (784, 1))\n', (5547, 5560), True, 'import numpy as np\n'), ((5652, 5675), 'numpy.reshape', 'np.reshape', (['x', '(784, 1)'], {}), '(x, (784, 1))\n', (5662, 5675), True, 'import numpy as np\n'), ((152, 162), 'numpy.exp', 'np.exp', (['(-z)'], {}), '(-z)\n', (158, 162), True, 'import numpy as np\n'), ((770, 791), 'numpy.random.randn', 'np.random.randn', (['y', '(1)'], {}), '(y, 1)\n', (785, 791), True, 'import numpy as np\n'), ((834, 855), 'numpy.random.randn', 'np.random.randn', (['y', 'x'], {}), '(y, x)\n', (849, 855), True, 'import numpy as np\n'), ((1456, 1485), 'random.shuffle', 'random.shuffle', (['training_data'], {}), '(training_data)\n', (1470, 1485), False, 'import random\n'), ((2214, 2231), 'numpy.zeros', 'np.zeros', (['b.shape'], {}), '(b.shape)\n', (2222, 2231), True, 'import numpy as np\n'), ((2273, 2290), 'numpy.zeros', 'np.zeros', (['w.shape'], {}), '(w.shape)\n', (2281, 2290), True, 'import numpy as np\n'), ((3035, 3052), 'numpy.zeros', 'np.zeros', (['b.shape'], {}), '(b.shape)\n', (3043, 3052), True, 'import numpy as np\n'), ((3094, 3111), 'numpy.zeros', 'np.zeros', (['w.shape'], {}), '(w.shape)\n', (3102, 3111), True, 'import numpy as np\n'), ((3392, 3413), 'numpy.dot', 'np.dot', (['w', 'activation'], {}), '(w, activation)\n', (3398, 3413), True, 'import numpy as np\n'), ((1069, 1081), 'numpy.dot', 'np.dot', (['w', 'a'], {}), '(w, a)\n', (1075, 1081), True, 'import numpy as np\n')]
""" Problem 81 ========== """ import numpy as np def load_matrix(filename): file = open(filename, 'r') matrix = [] for line in file: int_line = [int(x) for x in line.split(',')] matrix.append(int_line) file.close() return matrix def minimal_path(M): n = len(M) P = np.inf * np.ones((n, n), dtype=np.int) P[0][0] = M[0][0] for i in range(1, n): P[i][0] = M[i][0] + P[i-1][0] for j in range(1, n): P[0][j] = M[0][j] + P[0][j-1] for i in range(1, n): for j in range(1, n): P[i][j] = M[i][j] + min(P[i-1][j], P[i][j-1]) return P def main(): matrix = load_matrix('data/p081_matrix.txt') print(matrix) print(minimal_path(matrix)) if __name__ == "__main__": main()
[ "numpy.ones" ]
[((323, 352), 'numpy.ones', 'np.ones', (['(n, n)'], {'dtype': 'np.int'}), '((n, n), dtype=np.int)\n', (330, 352), True, 'import numpy as np\n')]
import os import numpy import keras import sklearn import preprocessing import plotting_utils class EvaluateModel: model_path = 'trained_model' model = '' def __init__( self, ): self.preprocessor = preprocessing.preprocessing.Preprocessing() def run( self, dataset, labels, hyperparameters, ): self.load_model() samples_pad_sequences = self.preprocessing( dataset=dataset, hyperparameters=hyperparameters, ) predictions = self.model.predict( samples_pad_sequences, batch_size=128, verbose=1, ) self.calculate_mean_auc( targets_predictions=predictions, targets_true=dataset[labels], ) roc_plotter = plotting_utils.plot_roc_curve.RocCurvePlotter() roc_plotter.plot( targets_predictions=predictions, targets_true=dataset[labels], ) def calculate_mean_auc( self, targets_predictions, targets_true, ): auc = [0] * 6 for label_index, label in enumerate(targets_true.columns): label_prediction = [ targets_prediction[label_index] for targets_prediction in targets_predictions ] auc[label_index] = sklearn.metrics.roc_auc_score( y_true=targets_true[label], y_score=label_prediction, ) print('Mean auc - {mean_auc}'.format( mean_auc=int(numpy.mean(auc) * 1000) / 1000 )) def load_model( self, ): json_file = open( os.path.join( 'trained_models', 'model.json', ), 'r', ) loaded_model_json = json_file.read() json_file.close() self.model = keras.models.model_from_json(loaded_model_json) self.model.load_weights( os.path.join( 'trained_models', 'model.h5', ) ) self.model.summary() print('Loaded model from disk') def preprocessing( self, dataset, hyperparameters, ): dataset['comment_text'] = self.preprocessor.get_cleaned_comments( dataset['comment_text'], ) self.preprocessor.initialize_tokenizer( comment_text=dataset['comment_text'], num_words=hyperparameters['max_features'], ) samples_pad_sequences = self.preprocessor.get_pad_sequences( dataset['comment_text'], maxlen=hyperparameters['maxlen'] ) return samples_pad_sequences
[ "plotting_utils.plot_roc_curve.RocCurvePlotter", "sklearn.metrics.roc_auc_score", "preprocessing.preprocessing.Preprocessing", "keras.models.model_from_json", "numpy.mean", "os.path.join" ]
[((233, 276), 'preprocessing.preprocessing.Preprocessing', 'preprocessing.preprocessing.Preprocessing', ([], {}), '()\n', (274, 276), False, 'import preprocessing\n'), ((822, 869), 'plotting_utils.plot_roc_curve.RocCurvePlotter', 'plotting_utils.plot_roc_curve.RocCurvePlotter', ([], {}), '()\n', (867, 869), False, 'import plotting_utils\n'), ((1908, 1955), 'keras.models.model_from_json', 'keras.models.model_from_json', (['loaded_model_json'], {}), '(loaded_model_json)\n', (1936, 1955), False, 'import keras\n'), ((1371, 1459), 'sklearn.metrics.roc_auc_score', 'sklearn.metrics.roc_auc_score', ([], {'y_true': 'targets_true[label]', 'y_score': 'label_prediction'}), '(y_true=targets_true[label], y_score=\n label_prediction)\n', (1400, 1459), False, 'import sklearn\n'), ((1696, 1740), 'os.path.join', 'os.path.join', (['"""trained_models"""', '"""model.json"""'], {}), "('trained_models', 'model.json')\n", (1708, 1740), False, 'import os\n'), ((2001, 2043), 'os.path.join', 'os.path.join', (['"""trained_models"""', '"""model.h5"""'], {}), "('trained_models', 'model.h5')\n", (2013, 2043), False, 'import os\n'), ((1574, 1589), 'numpy.mean', 'numpy.mean', (['auc'], {}), '(auc)\n', (1584, 1589), False, 'import numpy\n')]
""" This module provides a series of tools that will be used for the study of the Scanning Strategy of the LSPE/STRIP experiment. """ import healpy as hp import numpy as np from astropy import units as u import time as timing from astropy.coordinates import SkyCoord, EarthLocation, AltAz, ICRS from astropy.time import Time ### INSTRUMENT CHARACTERISTICS ### sampling_rate = 50 #Hz ### ### LOCATION INFORMATION ### LAT = np.array([28, 16, 24]) #deg LONG = np.array([-16, 38, 32]) #deg Height = 2400 #m ### ### TIME INFORMATION ### LCT_start = (0, 0, 0) #h, m, s LCD_start = (1, 1, 2015) #d, m, y UTC, DST = (0 , 0) #h obs_time = (1, 0, 0, 0, 0) #y, d, h, m, s ### def period2sec(years=0, days=0, hours=0, min=0, sec=0, sidereal=False): """ It converts a period of time in seconds. If sidereal=True it returns the mean sidereal time (sec); otherwise it returns the mean solar time (sec). Assumptions (from: "An introduction to modern astrophysics", (<NAME>), 2nd Ed.): 1 min = 60 sec 1 hour = 60 min 1 (mean) solar day = 24 hours 1 (mean) sidereal day = 23.93447 (23h 56m 4.1s) (with precession of the equinoxes) 1 solar year = 365 solar days *Different from (Carroll, Ostlie) 1 (mean) sidereal year = 365.24219 solar days (without precession of the equinoxes) 1 (mean) sidereal year = 365.25631 solar days (with precession of the equinoxes) N.B. (<NAME>) assumes 1 (mean) solar year = 365.24219 solar days. This function takes into account the precession of the equinoxes. """ if sidereal: return np.around( ((((years * 365.25631 * 24) + (days * 23.93447)) + hours) * 60 + min) * 60 + sec) return np.around((((years * 365 + days) * 24 + hours) * 60 + min) * 60 + sec) def sex2dec(angles, radians=False): """ It converts angles (or time) from sexagesimal to decimal and then radians (if radians = True). Example ------- >>> 16°30'35" >>> sex2dec(np.array([16, 30, 35])) = 16.509722° = 0.28815 rad """ if len(angles.shape) == 1: sign = -1 if np.sum(angles<0) == 1 else 1 deg, min, sec = angles[0], angles[1], angles[2] else: sign = np.ones(len(angles)) sign[np.sum(angles<0, axis=1) == 1] = -1 deg = angles[..., 0] min = angles[..., 1] sec = angles[..., 2] if radians: return np.radians((((sec / 60) + min) / 60) + np.abs(deg)) * sign return ((((sec / 60) + min) / 60) + np.abs(deg)) * sign def dec2sex(t): """ It converts times (or angles) from decimal to sexagesimal. Example ------- >>> 17.2563888888888 hours >>> decimal2sexagesimal(17.2563888888888) = np.array([17, 15, 23]) [hours, min, sec] if times >>> decimal2sexagesimal(17.2563888888888) = np.array([17, 15, 23]) [deg, min, sec] if angles """ sign = t / np.abs(t) h = np.floor(np.abs(t)) m = np.floor((np.abs(t) - h) * 60) s = (((np.abs(t) - h) * 60) - m) * 60 if np.array([t]).shape[-1] == 1: return np.column_stack((np.floor(h) * sign, m, s))[0] return np.column_stack((np.floor(h) * sign, m, s)) def degrees2hours(angles, decimal=False): """ It converts angles from degrees to hours. Example ------- >>> 23° 27' 43.56" >>> degrees2hours(np.array([23, 27, 43.56]), decimal=True) = 1.56414 hours >>> degrees2hours(np.array([23, 27, 43.56])) = np.array([1, 33, 50.904]) [hours, min, sec] """ decimal_degrees = sex2dec(angles) h = 24 * decimal_degrees / 360 if decimal: return h return dec2sex(h) def hours2degrees(angles, decimal=False): """ It converts angles from hours to degrees. Example ------- >>> 1h 33min 50.904sec >>> hours2degrees(np.array([1, 33, 50.904]), decimal=True) = 1.56414 hours >>> hours2degrees(np.array([1, 33, 50.904])) = np.array([1, 33, 50.904]) [hours, min, sec] """ decimal_hours = sex2dec(angles) d = 360 * decimal_hours / 24 if decimal: return d return dec2sex(d) def GreenwichCalendarDate2JulianDate(GD, GM, GY): """ It converts the Greenwich Calendar Date (GCD) to the Julian Date. Parameters ---------- GD : float It is the day in the GCD system. GM : integer It is the month in the GCD system. GY : integer It is the year in the GCD system. Returns ------- out : float """ if GM < 3 : y, m = (GY - 1, GM + 12) else: y, m = (GY, GM) B = 2 - np.int(y / 100) + np.int(np.int(y / 100) / 4) if GY < 1582: if GM < 10: if GY < 15: B = 0 if y < 0 : C = np.int((365.25 * y) - 0.75) else: C = np.int(365.25 * y) D = np.int(30.6001 * (m + 1)) return B + C + D + GD + 1720994.5 def LocalCivilTime2GreenwichCalendarDay(LCT, LCD, UTC=0, DST=0): """ It converts the Local Civil Time (LCT) to the Greenwich Calendar Date. Parameters ---------- LCT : tuple of length 3 It is the Local Civil Time in the format (hours, minutes, seconds). LCD : tuple of length 3 It is the Local Civil Day in the format (day, month, year). UTC : integer in the range (-12, 12) It is the number which describes the Earth time zone with respect to the Greenwich time zone (UTC=0). DST : integer in the range (0, 1) It is the number which says if the Daylight Saving Time is on or off. Returns ------- out : float, integer, integer [day, month, year] """ (h, m, s), (D, M, Y) = LCT, LCD UniversalTime = (h - DST - UTC) + m / 60 + s / 3600 return UniversalTime / 24 + D, M, Y def LocalCivilTime2JulianDay(LCT, LCD, UTC=0, DST=0): """ It converts the Local Civil Time (LCT) to the Julian Day. Parameters ---------- LCT : tuple of length 3 It is the Local Civil Time in the format (hours, minutes, seconds). LCD : tuple of length 3 It is the Local Civil Day in the format (day, month, year). UTC : integer in the range (-12, 12) It is the number which describes the Earth time zone with respect to the Greenwich time zone (UTC=0). DST : integer in the range (0, 1) It is the number which says if the Daylight Saving Time is on or off. Returns ------- out : float """ GreenwichCalendarDay, M, Y = LocalCivilTime2GreenwichCalendarDay(LCT, LCD, UTC=UTC, DST=DST) return GreenwichCalendarDate2JulianDate(GreenwichCalendarDay, M, Y) def LocalCivilTime2LocalSiderealTime(LCT, LCD, LONG, UTC=0, DST=0): """ It converts the Local Civil Time (LCT) to the Local Sidereal Time. Parameters ---------- LCT : tuple of length 3 It is the Local Civil Time in the format (hours, minutes, seconds). LCD : tuple of length 3 It is the Local Civil Day in the format (day, month, year). LONG : tuple of length 3 It is the observation site Longitude in the format (deg, min, sec). UTC : integer in the range (-12, 12) It is the number which describes the Earth time zone with respect to the Greenwich time zone (UTC=0). DST : integer in the range (0, 1) It is the number which says if the Daylight Saving Time is on or off. Returns ------- out : float """ jd = LocalCivilTime2JulianDay(LCT, LCD, UTC=0, DST=0) d = jd - 2451543.5 w = 282.9404 + 4.70935e-5 * d M = 356.0470 + 0.9856002585 * d L = w + np.mod(M, 360) GMST0 = np.mod(L, 360)/15 + 12 rest = jd - np.floor(jd) + 0.5 UT = (rest - np.floor(rest)) * 24 LST = np.mod(GMST0, 24) + UT + sex2dec(LONG)/15 return dec2sex(np.mod(LST, 24)) def get_nside_eff(fwhm_beam): """ It returns the nside corresponding to the given angular resolution of the beam. N.B. The results are slightly differents from hp.nside2resol. A cross-check is strongly raccommended. """ fwhm = sex2dec(fwhm_beam, radians=True) area_pix_eff = np.pi * fwhm**2 / 4 N_pix_eff = 4 * np.pi / area_pix_eff nside_eff = np.sqrt(N_pix_eff / 12) return 2**(np.int(np.log2(nside_eff)) + 1) def get_full_fp(fp_theta_path, fp_phi_path): """ It reads 2 files.txt which are the focal plane coordinates in spherical coordinates of the first 4 modules of STRIP (I, Y, O, R). It returns the full focal plane coordinates in cartesian coordinates, since the last 3 modules (V, B, G) are symmetrical with respect the central one. IT returns the complete focal plane coordinates and the total number of horns in the focal plane with the following conventions: x_fp[0:7] = module named I x_fp[7:14] = module named Y x_fp[14:21] = module named O x_fp[21:28] = module named R x_fp[28:35] = module named v x_fp[35:42] = module named B x_fp[42:49] = module named G Returns ------- out : numpy array of shape (49, 3), float """ theta = np.loadtxt(fp_theta_path) phi = np.loadtxt(fp_phi_path) full_theta = np.append(theta, [theta[-7:], theta[-14:-7], theta[-21:-14]]) full_theta[29:34] = full_theta[29:34][::-1] full_theta[36:41] = full_theta[36:41][::-1] full_theta[43:48] = full_theta[43:48][::-1] full_phi = np.append(phi, [-phi[-7:], -phi[-14:-7], -phi[-21:-14]]) full_phi[29:34] = full_phi[29:34][::-1] full_phi[36:41] = full_phi[36:41][::-1] full_phi[43:48] = full_phi[43:48][::-1] x_fp = hp.ang2vec(full_theta, full_phi) return x_fp, len(x_fp) def get_full_fp_polarization_angles(fp_psi_path): """ It reads 1 files.txt which cointains the focal plane polarization angles for the first 4 modules of STRIP (I, Y, O, R). It returns the full focal plane polarization angles, since the last 3 modules (V, B, G) are symmetrical with respect the central one. It uses the same conventions of get_full_fp function. And, furthermore, it uses the following conventions to construct the polarization versor: x = np.cos(psi) y = np.sin(psi) z = 0 Returns ------- out : numpy array of shape (49,), numpy array of shape (49, 3) """ psi = np.loadtxt(fp_psi_path) full_psi = np.append(psi, [-psi[-7:], -psi[-14:-7], -psi[-21:-14]]) full_psi[29:34] = full_psi[29:34][::-1] full_psi[36:41] = full_psi[36:41][::-1] full_psi[43:48] = full_psi[43:48][::-1] polarization_versors = np.column_stack((np.cos(full_psi), np.sin(full_psi), np.full_like(full_psi, 0))) return full_psi, polarization_versors def get_timeJD(LCT_start, LCD_start, sampling_rate, obs_time, UTC=0, DST=0, day=None): """ It returns the total observation time and the time samples expressed in seconds, and the Julian Dates starting from a given Local Civil Time and Day. Parameters ---------- LCT_start : tuple of length 3 It is the Local Civil Time in the format (hours, minutes, seconds). LCD_start : tuple of length 3 It is the Local Civil Day in the format (day, month, year). sampling_rate : float, Hertz It is the instrument sampling rate. obs_time : tuple of lenght 5 It is the observation time in the format (years, days, hours, minutes, seconds) UTC : integer in the range (-12, 12) It is the number which describes the Earth time zone with respect to the Greenwich time zone (UTC=0). DST : integer in the range (0, 1) It is the number which says if the Daylight Saving Time is on or off. day : float, default = None In the case of observation time greater than 1 day it is the observation day at which the time is computed. Otherwise, it must be setted to None. If None it will return the time computed over all the given observation time. Returns ------- out : float, numpy array of shape (obs_time * sampling_rate,) or (86400 * sampling_rate,) if day is not None, numpy array of shape (obs_time * sampling_rate,) or (86400 * sampling_rate,) if day is not None """ obs_t = period2sec(years=obs_time[0], days=obs_time[1], hours=obs_time[2], min=obs_time[3], sec=obs_time[4], sidereal=False) JD_start = LocalCivilTime2JulianDay(LCT_start, LCD_start, UTC=UTC, DST=DST) LCT_step = (0, 0, 1 / sampling_rate) JD_step = ( LocalCivilTime2JulianDay(np.array(LCT_start) + np.array(LCT_step), LCD_start, UTC=UTC, DST=DST) - LocalCivilTime2JulianDay(LCT_start, LCD_start, UTC=UTC, DST=DST)) if day is None: time = np.linspace(0, obs_t, obs_t * sampling_rate + 1) #sec JD = np.arange(JD_start, JD_start + JD_step * len(time), JD_step) else: if obs_t < 86400: raise ValueError("If the obs_time is lower than 1 day the 'day' parameter must be None") t = period2sec(days=1) time = np.linspace((day - 1) * t, day * t, t * sampling_rate + 1) JD = np.arange(JD_start + JD_step * (len(time) * (day - 1) - 1), JD_start + JD_step * len(time) * day, JD_step)[:-1] return obs_t, time[:-1], JD[:-1] def get_location(LAT, LONG, Height): """ It returns an astropy object which gets information about the location of observation site. Parameters ---------- LAT : tuple of length 3 It is the observation site Latitude in the format (deg, min, sec). LONG : tuple of length 3 It is the observation site Longitude in the format (deg, min, sec). Height : integer, meters It is the observation site Height expressed in meters. """ Lat = sex2dec(LAT) #deg Long = sex2dec(LONG) #deg return EarthLocation(lon=Long, lat=Lat, height=Height) def spin_generator(time, rpm): """ It returns the phi angle in the case of spinning of the telescope. Parameters ---------- time : numpy array of shape (obs_time * sampling rate), sec It is the time sample expressed in seconds. rpm : integer It is the number of revolutions per minute of the telescope. Returns ------- out : numpy array of shape (obs_time * sampling_rate) or (86400 * sampling_rate) if day is not None """ spin_freq = rpm / 60 #Hz spin_T = 1 / spin_freq #sec return 2 * np.pi * (time / spin_T - (time / spin_T).astype(int)) def euler_rotation_matrix(phi, theta, psi=0): """ It returns the rotation matrix correspondig to the rotation of the angles phi, theta, phi about respectively the axes (z, x, z). So that, the following rotation is performed: R_z(phi) * R_x(theta) * R_z(psi) Parameters ---------- phi : float or numpy array, radians Rotation about the x axis. theta : float or numpy array, radians Rotation about the z axis. psi : float or numpy array, radians, default = 0 Rotation about the x axis. Returns ------- out : numpy array of shape (obs_time * sampling_rate) """ c1, c2, c3 = (np.cos(phi), np.cos(theta), np.cos(psi)) s1, s2, s3 = (np.sin(phi), np.sin(theta), np.sin(psi)) matrix = np.array([[c1*c3 - c2*s1*s3, -c1*s3 - c2*c3*s1, s1*s2], [c3*s1 + c1*c2*s3, c1*c2*c3 - s1*s3, -c1*s2], [s2*s3, c3*s2, c2]]) return np.rollaxis(matrix, 2, 0) def get_engine_rotations(time, rpm, zenith_distance, polarization_angle): """ It returns the temporal sequence of the engine rotation angles. It supposes that the zenith distance and the polarization angle are constants while the azimth angle spins around the z axis. Parameters ---------- time : numpy array of shape (obs_time * sampling rate), sec It is the time sample expressed in seconds. rpm : integer It is the number of revolutions per minute of the telescope. zenith_distance : integer, degrees It is the zenith distance in the telescope frame of reference. polarization_angle : integer, degrees It is the polarization angle in the telescope frame of reference. Returns ------- out : numpy array of shape (obs_time * sampling_rate), numpy array of shape (obs_time * sampling_rate), numpy array of shape (obs_time * sampling_rate) """ theta = np.full_like(time, np.radians(zenith_distance)) #rad phi = spin_generator(time, rpm) #rad psi = np.full_like(time, np.radians(polarization_angle)) #rad return theta, phi, psi def get_fp_rotations(phi, theta, psi, x_fp, n_horns, time, n=None, cartesian=False): """ It returns the temporal sequence of pointings for each horn. Parameters ---------- phi : numpy array of shape (obs_time * sampling_rate), radians The Azimith angle. theta : numpy array of shape (obs_time * sampling_rate), radians The Zenith distance. psi : numpy array of shape (obs_time * sampling_rate), radians The polarization angle. x_fp : numpy array of shape (n_horns, 3) They are the positions (versors) of the horns in the frame of reference of the focal plane (the one in which the central horn points towards the local Zenith with versor (0, 0, 1)). n_honrs : integer It is the total number of horns. time : numpy array of shape (obs_time * sampling rate), sec It is the time sample expressed in seconds. n : integer in the range (0, n_horns - 1), default = None It is the horn for which the pointings are computed. If None, will be returned the pointings for all the horns. cartesian : boolean, dafault = False If True will be returned the pointings in cartesian coordinates. Otherwise, the spherical coordinates of the pointings will be returned. Returns ------- out : numpy array of shape (n_horns, obs_time * sampling_rate, 2), numpy array of shape (n_horns, obs_time * sampling_rate, 3) if cartesian, numpy array of shape (obs_time * sampling_rate, 2) if n, numpy array of shape (obs_time * sampling_rate, 3) if n and cartesian """ tc, tw = (timing.clock(), timing.time()) fp_rotations = euler_rotation_matrix(phi, theta, psi) if n is None: fp_pointings = np.sum(fp_rotations[None, ...] * x_fp[:, None, None, :], axis=-1) fp_pointings_spherical = np.column_stack(hp.vec2ang(fp_pointings)).reshape( n_horns, len(time), 2) else: fp_pointings = np.sum(fp_rotations * x_fp[n, None, :], axis=-1) fp_pointings_spherical = np.column_stack(hp.vec2ang(fp_pointings)) clock_time, wall_time = (timing.clock() - tc, timing.time() - tw) print ('fp conversion clock time [sec]:', clock_time, '\n', 'fp conversion wall time [sec]:', wall_time) if cartesian: return fp_pointings return fp_pointings_spherical def get_horizon_coordinates(fp_pointings_spherical): """ It converts from spherical to Horizon coordinates, with the conventions: Altitute = np.pi / 2 - zenith angle (theta) Azimuth = 2 * np.pi - phi Parameters ---------- fp_pointings_spherical : numpy array of shape (..., 2), radians They are the spherical coordinates (theta, phi) that will be converted. Returns ------- out : numpy array of shape (..., ), numpy array of shape (..., ) """ Alt = np.pi/2 - fp_pointings_spherical[..., 0] #rad Az = 2 * np.pi - fp_pointings_spherical[..., 1] #rad return Alt, Az def get_practical_icrs_coordinates(JD, loc, Alt, Az, hours=False): """ It converts from Horizon to Equatorial (icrs) coordinates, according to the astropy conventions. Parameters ---------- JD : numpy array of shape (obs_time * sampling_rate) or (n_horns, obs_time * sampling_rate) The Julian Dates corresponding to the temporal sequence of pointings. loc : astropy EarthLocation object An astropy object which gets information about the location of observation site. Alt : numpy array of shape (obs_time * sampling_rate) or (n_horns, obs_time * sampling_rate) The temporal sequence of Altitude. Az : numpy array of shape (obs_time * sampling_rate) or (n_horns, obs_time * sampling_rate) The temporal sequence of Azimuth. hours : boolean, default=False If True it returns the Right Ascension in hours; otherwise decimal. Returns ------- out : numpy array of shape (..., ), numpy array of shape (..., ) """ tc, tw = (timing.clock(), timing.time()) LST = Time(JD, format='jd', location=loc).sidereal_time('mean').value Lat = loc.lat.rad Long = loc.lon.rad Dec = np.arcsin(np.sin(Alt) * np.sin(Lat) + np.cos(Alt) * np.cos(Lat) * np.cos(Az)) HourAngle = np.arccos((np.sin(Alt) - np.sin(Dec) * np.sin(Lat)) / (np.cos(Dec) * np.cos(Lat))) index = np.sin(Az) < 0 h = (360 - np.degrees(HourAngle)) / 15 h[index] = np.degrees(HourAngle[index]) / 15 Ra = LST - h Ra[Ra < 0] += 24 clock_time, wall_time = (timing.clock() - tc, timing.time() - tw) print ('practical icrs conversion clock time [sec]:', clock_time, '\n', 'practical icrs conversion wall time [sec]:', wall_time) if hours: return Dec, Ra return Dec, np.radians(360 * Ra / 24) def get_icrs_coordinates(JD, loc, Alt, Az): """ It converts from Horizon to Equatorial (icrs) coordinates, according to the astropy conventions. Parameters ---------- JD : numpy array of shape (obs_time * sampling_rate) or (n_horns, obs_time * sampling_rate) The Julian Dates corresponding to the temporal sequence of pointings. loc : astropy EarthLocation object An astropy object which gets information about the location of observation site. Alt : numpy array of shape (obs_time * sampling_rate) or (n_horns, obs_time * sampling_rate) The temporal sequence of Altitude. Az : numpy array of shape (obs_time * sampling_rate) or (n_horns, obs_time * sampling_rate) The temporal sequence of Azimuth. Returns ------- out : numpy array of shape (..., ), numpy array of shape (..., ) """ tc, tw = (timing.clock(), timing.time()) times = Time(JD, format='jd', location=loc) pointings = SkyCoord(alt=Alt*u.rad, az=Az*u.rad, obstime=times, frame='altaz', location=loc) Ra = pointings.transform_to('icrs').ra.rad #rad Dec = pointings.transform_to('icrs').dec.rad #rad clock_time, wall_time = (timing.clock() - tc, timing.time() - tw) print ('icrs conversion clock time [sec]:', clock_time, '\n', 'icrs conversion wall time [sec]:', wall_time) return Dec, Ra def get_polarization_angles(phi, theta, psi, x_fp_pol_versors, n_horns, time, n=None): """ It returns the polarization angles projected in the sky. Parameters ---------- phi : float or numpy array, radians Rotation about the x axis. theta : float or numpy array, radians Rotation about the z axis. psi : float or numpy array, radians, default = 0 Rotation about the x axis. x_fp_pol_versors : numpy array of shape (n_horns, 3) They are the polarization versors for each horn in the frame of reference of the focal plane (the one in which the central horn points towards the local Zenith with versor (0, 0, 1)). n_honrs : integer It is the total number of horns. time : numpy array of shape (obs_time * sampling rate), sec It is the time sample expressed in seconds. n : integer in the range (0, n_horns - 1), default = None It is the horn for which the pointings are computed. If None, will be returned the pointings for all the horns. Returns ------- out : numpy array of shape (n_horns, obs_time * sampling_rate) or numpy array of shape (obs_time * sampling_rate, ) if n """ fp_pol_pointings = get_fp_rotations(phi, theta, psi, x_fp_pol_versors, n_horns, time, n=n, cartesian=True) #rad return np.arctan2(fp_pol_pointings[..., 1], fp_pol_pointings[..., 0]) def get_scanning_strategy(obs_time, sampling_rate, zenith_distance, boresight_angle, rpm, n=None, day=None, LCT_start=(0, 0, 0), LCD_start=(1, 1, 2018), UTC=0, DST=0, LAT=np.array([28, 16, 24]), LONG=np.array([-16, 38, 32]), Height=2400, fp_theta_path='./fp_theta.txt', fp_phi_path='./fp_phi.txt', fp_psi_path='./fp_psi.txt'): """ It returns all the parameters of the STRIP Scanning Strategy, in the following order: - The location of the horns in Cartesian coordinates : x_fp; - The total number of horns : n_honrs; - The time sample : time; - The Julian Dates sample : JD; - The sample of the engine rotation angles : theta, phi, psi; - The focal plane pointings sample in spherical coordinates : fp_pointings_spherical; - The Horizon coordinates : Alt, AZ; - The Equatorial (icrs) coordinates : Dec, Ra. In particular, if n is specified will be returned only the values for the horn n. Otherwise, will be returned the values for all the horns. In the same way, if day is specified will be returned the values for that obsarvation day. Otherwise, will be returned the values for the whole observation period. Parameters ---------- obs_time : tuple of lenght 5 It is the observation time in the format (years, days, hours, minutes, seconds) sampling_rate : float, Hertz It is the instrument sampling rate. zenith_distance : integer, degrees It is the zenith distance in the telescope frame of reference. boresight_angle : integer, degrees It is the polarization angle in the telescope frame of reference. rpm : integer It is the number of revolutions per minute of the telescope. n : integer in the range (0, n_horns - 1), default = None It is the horn for which the pointings are computed. If None, will be returned the pointings for all the horns. day : float, default = None In the case of observation time greater than 1 day it is the observation day at which the time is computed. Otherwise, it must be setted to None. If None it will return the time computed over all the given observation time. LCT_start : tuple of length 3 It is the Local Civil Time in the format (hours, minutes, seconds). LCD_start : tuple of length 3 It is the Local Civil Day in the format (day, month, year). UTC : integer in the range (-12, 12) It is the number which describes the Earth time zone with respect to the Greenwich time zone (UTC=0). DST : integer in the range (0, 1) It is the number which says if the Daylight Saving Time is on or off. LAT : tuple of length 3 It is the observation site Latitude in the format (deg, min, sec). LONG : tuple of length 3 It is the observation site Longitude in the format (deg, min, sec). Height : integer, meters It is the observation site Height expressed in meters. fp_theta_path : string It is the path to the file.txt where are stored the theta positions of the focal plane horns. fp_phi_path : string It is the path to the file.txt where are stored the phi positions of the focal plane horns. fp_psi_path : string It is the path to the file.txt where are stored the polarization angles of the focal plane horns. Returns ------- out : numpy array of shape (n_horns, 3), numpy array of shape (n_horns, ), float, numpy array of shape (obs_time * sampling_rate) or (86400 * sampling_rate) if day, numpy array of shape (obs_time * sampling_rate) or (86400 * sampling_rate) if day, numpy array of shape (obs_time * sampling_rate) or (86400 * sampling_rate) if day, numpy array of shape (obs_time * sampling_rate) or (86400 * sampling_rate) if day, numpy array of shape (obs_time * sampling_rate) or (86400 * sampling_rate) if day, numpy array of shape (obs_time * sampling_rate, 2) or (86400 * sampling_rate, 2) if day, numpy array of shape (obs_time * sampling_rate) or (86400 * sampling_rate) if day, numpy array of shape (obs_time * sampling_rate) or (86400 * sampling_rate) if day, numpy array of shape (obs_time * sampling_rate) or (86400 * sampling_rate) if day, numpy array of shape (obs_time * sampling_rate) or (86400 * sampling_rate) if day, numpy array of shape (obs_time * sampling_rate) or (86400 * sampling_rate) if day """ ### FOCAL PLANE LOAD ### x_fp, n_horns = get_full_fp(fp_theta_path, fp_phi_path) x_fp_pol_angles, x_fp_pol_versors = get_full_fp_polarization_angles(fp_psi_path) ### GET LOCATION ### loc = get_location(LAT=LAT, LONG=LONG, Height=Height) ### GET TIME INFORMATION ### obs_t, time, JD = get_timeJD(LCT_start, LCD_start, sampling_rate, obs_time, UTC=UTC, DST=DST, day=day) ### GET ENGINE ROTATIONS ### theta, phi, psi = get_engine_rotations(time, rpm, zenith_distance, boresight_angle) #rad ### GET FOCAL PLANE POINTINGS ### fp_pointings_spherical = get_fp_rotations(phi, theta, psi, x_fp, n_horns, time, n=n) #rad ### GET HORIZON COORDINATES ### Alt, Az = get_horizon_coordinates(fp_pointings_spherical) #rad ### EQUATORIAL (ICRS) COORDINATES CONVERSION ### Dec, Ra = get_practical_icrs_coordinates(JD, loc, Alt, Az) #rad ### GET POLARIZATION ANGLES ### polarization_angles = get_polarization_angles(phi, theta, psi, x_fp_pol_versors, n_horns, time, n=n) return (x_fp, x_fp_pol_angles, n_horns, time, JD, theta, phi, psi, fp_pointings_spherical, Alt, Az, Dec, Ra, polarization_angles)
[ "numpy.arctan2", "numpy.abs", "numpy.sum", "healpy.vec2ang", "numpy.floor", "numpy.around", "numpy.sin", "numpy.full_like", "numpy.degrees", "time.clock", "numpy.append", "numpy.int", "numpy.loadtxt", "numpy.linspace", "numpy.rollaxis", "numpy.radians", "healpy.ang2vec", "astropy.t...
[((427, 449), 'numpy.array', 'np.array', (['[28, 16, 24]'], {}), '([28, 16, 24])\n', (435, 449), True, 'import numpy as np\n'), ((462, 485), 'numpy.array', 'np.array', (['[-16, 38, 32]'], {}), '([-16, 38, 32])\n', (470, 485), True, 'import numpy as np\n'), ((1701, 1771), 'numpy.around', 'np.around', (['((((years * 365 + days) * 24 + hours) * 60 + min) * 60 + sec)'], {}), '((((years * 365 + days) * 24 + hours) * 60 + min) * 60 + sec)\n', (1710, 1771), True, 'import numpy as np\n'), ((4788, 4813), 'numpy.int', 'np.int', (['(30.6001 * (m + 1))'], {}), '(30.6001 * (m + 1))\n', (4794, 4813), True, 'import numpy as np\n'), ((8191, 8214), 'numpy.sqrt', 'np.sqrt', (['(N_pix_eff / 12)'], {}), '(N_pix_eff / 12)\n', (8198, 8214), True, 'import numpy as np\n'), ((9074, 9099), 'numpy.loadtxt', 'np.loadtxt', (['fp_theta_path'], {}), '(fp_theta_path)\n', (9084, 9099), True, 'import numpy as np\n'), ((9110, 9133), 'numpy.loadtxt', 'np.loadtxt', (['fp_phi_path'], {}), '(fp_phi_path)\n', (9120, 9133), True, 'import numpy as np\n'), ((9151, 9212), 'numpy.append', 'np.append', (['theta', '[theta[-7:], theta[-14:-7], theta[-21:-14]]'], {}), '(theta, [theta[-7:], theta[-14:-7], theta[-21:-14]])\n', (9160, 9212), True, 'import numpy as np\n'), ((9372, 9428), 'numpy.append', 'np.append', (['phi', '[-phi[-7:], -phi[-14:-7], -phi[-21:-14]]'], {}), '(phi, [-phi[-7:], -phi[-14:-7], -phi[-21:-14]])\n', (9381, 9428), True, 'import numpy as np\n'), ((9572, 9604), 'healpy.ang2vec', 'hp.ang2vec', (['full_theta', 'full_phi'], {}), '(full_theta, full_phi)\n', (9582, 9604), True, 'import healpy as hp\n'), ((10274, 10297), 'numpy.loadtxt', 'np.loadtxt', (['fp_psi_path'], {}), '(fp_psi_path)\n', (10284, 10297), True, 'import numpy as np\n'), ((10313, 10369), 'numpy.append', 'np.append', (['psi', '[-psi[-7:], -psi[-14:-7], -psi[-21:-14]]'], {}), '(psi, [-psi[-7:], -psi[-14:-7], -psi[-21:-14]])\n', (10322, 10369), True, 'import numpy as np\n'), ((14044, 14091), 'astropy.coordinates.EarthLocation', 'EarthLocation', ([], {'lon': 'Long', 'lat': 'Lat', 'height': 'Height'}), '(lon=Long, lat=Lat, height=Height)\n', (14057, 14091), False, 'from astropy.coordinates import SkyCoord, EarthLocation, AltAz, ICRS\n'), ((15568, 15730), 'numpy.array', 'np.array', (['[[c1 * c3 - c2 * s1 * s3, -c1 * s3 - c2 * c3 * s1, s1 * s2], [c3 * s1 + c1 *\n c2 * s3, c1 * c2 * c3 - s1 * s3, -c1 * s2], [s2 * s3, c3 * s2, c2]]'], {}), '([[c1 * c3 - c2 * s1 * s3, -c1 * s3 - c2 * c3 * s1, s1 * s2], [c3 *\n s1 + c1 * c2 * s3, c1 * c2 * c3 - s1 * s3, -c1 * s2], [s2 * s3, c3 * s2,\n c2]])\n', (15576, 15730), True, 'import numpy as np\n'), ((15750, 15775), 'numpy.rollaxis', 'np.rollaxis', (['matrix', '(2)', '(0)'], {}), '(matrix, 2, 0)\n', (15761, 15775), True, 'import numpy as np\n'), ((23010, 23045), 'astropy.time.Time', 'Time', (['JD'], {'format': '"""jd"""', 'location': 'loc'}), "(JD, format='jd', location=loc)\n", (23014, 23045), False, 'from astropy.time import Time\n'), ((23062, 23150), 'astropy.coordinates.SkyCoord', 'SkyCoord', ([], {'alt': '(Alt * u.rad)', 'az': '(Az * u.rad)', 'obstime': 'times', 'frame': '"""altaz"""', 'location': 'loc'}), "(alt=Alt * u.rad, az=Az * u.rad, obstime=times, frame='altaz',\n location=loc)\n", (23070, 23150), False, 'from astropy.coordinates import SkyCoord, EarthLocation, AltAz, ICRS\n'), ((25090, 25152), 'numpy.arctan2', 'np.arctan2', (['fp_pol_pointings[..., 1]', 'fp_pol_pointings[..., 0]'], {}), '(fp_pol_pointings[..., 1], fp_pol_pointings[..., 0])\n', (25100, 25152), True, 'import numpy as np\n'), ((25378, 25400), 'numpy.array', 'np.array', (['[28, 16, 24]'], {}), '([28, 16, 24])\n', (25386, 25400), True, 'import numpy as np\n'), ((25407, 25430), 'numpy.array', 'np.array', (['[-16, 38, 32]'], {}), '([-16, 38, 32])\n', (25415, 25430), True, 'import numpy as np\n'), ((1585, 1674), 'numpy.around', 'np.around', (['(((years * 365.25631 * 24 + days * 23.93447 + hours) * 60 + min) * 60 + sec)'], {}), '(((years * 365.25631 * 24 + days * 23.93447 + hours) * 60 + min) *\n 60 + sec)\n', (1594, 1674), True, 'import numpy as np\n'), ((2881, 2890), 'numpy.abs', 'np.abs', (['t'], {}), '(t)\n', (2887, 2890), True, 'import numpy as np\n'), ((2908, 2917), 'numpy.abs', 'np.abs', (['t'], {}), '(t)\n', (2914, 2917), True, 'import numpy as np\n'), ((4711, 4736), 'numpy.int', 'np.int', (['(365.25 * y - 0.75)'], {}), '(365.25 * y - 0.75)\n', (4717, 4736), True, 'import numpy as np\n'), ((4761, 4779), 'numpy.int', 'np.int', (['(365.25 * y)'], {}), '(365.25 * y)\n', (4767, 4779), True, 'import numpy as np\n'), ((7597, 7611), 'numpy.mod', 'np.mod', (['M', '(360)'], {}), '(M, 360)\n', (7603, 7611), True, 'import numpy as np\n'), ((7791, 7806), 'numpy.mod', 'np.mod', (['LST', '(24)'], {}), '(LST, 24)\n', (7797, 7806), True, 'import numpy as np\n'), ((12903, 12951), 'numpy.linspace', 'np.linspace', (['(0)', 'obs_t', '(obs_t * sampling_rate + 1)'], {}), '(0, obs_t, obs_t * sampling_rate + 1)\n', (12914, 12951), True, 'import numpy as np\n'), ((13214, 13272), 'numpy.linspace', 'np.linspace', (['((day - 1) * t)', '(day * t)', '(t * sampling_rate + 1)'], {}), '((day - 1) * t, day * t, t * sampling_rate + 1)\n', (13225, 13272), True, 'import numpy as np\n'), ((15454, 15465), 'numpy.cos', 'np.cos', (['phi'], {}), '(phi)\n', (15460, 15465), True, 'import numpy as np\n'), ((15467, 15480), 'numpy.cos', 'np.cos', (['theta'], {}), '(theta)\n', (15473, 15480), True, 'import numpy as np\n'), ((15482, 15493), 'numpy.cos', 'np.cos', (['psi'], {}), '(psi)\n', (15488, 15493), True, 'import numpy as np\n'), ((15513, 15524), 'numpy.sin', 'np.sin', (['phi'], {}), '(phi)\n', (15519, 15524), True, 'import numpy as np\n'), ((15526, 15539), 'numpy.sin', 'np.sin', (['theta'], {}), '(theta)\n', (15532, 15539), True, 'import numpy as np\n'), ((15541, 15552), 'numpy.sin', 'np.sin', (['psi'], {}), '(psi)\n', (15547, 15552), True, 'import numpy as np\n'), ((16867, 16894), 'numpy.radians', 'np.radians', (['zenith_distance'], {}), '(zenith_distance)\n', (16877, 16894), True, 'import numpy as np\n'), ((16971, 17001), 'numpy.radians', 'np.radians', (['polarization_angle'], {}), '(polarization_angle)\n', (16981, 17001), True, 'import numpy as np\n'), ((18822, 18836), 'time.clock', 'timing.clock', ([], {}), '()\n', (18834, 18836), True, 'import time as timing\n'), ((18838, 18851), 'time.time', 'timing.time', ([], {}), '()\n', (18849, 18851), True, 'import time as timing\n'), ((18952, 19017), 'numpy.sum', 'np.sum', (['(fp_rotations[None, ...] * x_fp[:, None, None, :])'], {'axis': '(-1)'}), '(fp_rotations[None, ...] * x_fp[:, None, None, :], axis=-1)\n', (18958, 19017), True, 'import numpy as np\n'), ((19170, 19218), 'numpy.sum', 'np.sum', (['(fp_rotations * x_fp[n, None, :])'], {'axis': '(-1)'}), '(fp_rotations * x_fp[n, None, :], axis=-1)\n', (19176, 19218), True, 'import numpy as np\n'), ((21278, 21292), 'time.clock', 'timing.clock', ([], {}), '()\n', (21290, 21292), True, 'import time as timing\n'), ((21294, 21307), 'time.time', 'timing.time', ([], {}), '()\n', (21305, 21307), True, 'import time as timing\n'), ((21627, 21637), 'numpy.sin', 'np.sin', (['Az'], {}), '(Az)\n', (21633, 21637), True, 'import numpy as np\n'), ((21700, 21728), 'numpy.degrees', 'np.degrees', (['HourAngle[index]'], {}), '(HourAngle[index])\n', (21710, 21728), True, 'import numpy as np\n'), ((22039, 22064), 'numpy.radians', 'np.radians', (['(360 * Ra / 24)'], {}), '(360 * Ra / 24)\n', (22049, 22064), True, 'import numpy as np\n'), ((22967, 22981), 'time.clock', 'timing.clock', ([], {}), '()\n', (22979, 22981), True, 'import time as timing\n'), ((22983, 22996), 'time.time', 'timing.time', ([], {}), '()\n', (22994, 22996), True, 'import time as timing\n'), ((2498, 2509), 'numpy.abs', 'np.abs', (['deg'], {}), '(deg)\n', (2504, 2509), True, 'import numpy as np\n'), ((4553, 4568), 'numpy.int', 'np.int', (['(y / 100)'], {}), '(y / 100)\n', (4559, 4568), True, 'import numpy as np\n'), ((7624, 7638), 'numpy.mod', 'np.mod', (['L', '(360)'], {}), '(L, 360)\n', (7630, 7638), True, 'import numpy as np\n'), ((7663, 7675), 'numpy.floor', 'np.floor', (['jd'], {}), '(jd)\n', (7671, 7675), True, 'import numpy as np\n'), ((7699, 7713), 'numpy.floor', 'np.floor', (['rest'], {}), '(rest)\n', (7707, 7713), True, 'import numpy as np\n'), ((7730, 7747), 'numpy.mod', 'np.mod', (['GMST0', '(24)'], {}), '(GMST0, 24)\n', (7736, 7747), True, 'import numpy as np\n'), ((10546, 10562), 'numpy.cos', 'np.cos', (['full_psi'], {}), '(full_psi)\n', (10552, 10562), True, 'import numpy as np\n'), ((10564, 10580), 'numpy.sin', 'np.sin', (['full_psi'], {}), '(full_psi)\n', (10570, 10580), True, 'import numpy as np\n'), ((10625, 10650), 'numpy.full_like', 'np.full_like', (['full_psi', '(0)'], {}), '(full_psi, 0)\n', (10637, 10650), True, 'import numpy as np\n'), ((19268, 19292), 'healpy.vec2ang', 'hp.vec2ang', (['fp_pointings'], {}), '(fp_pointings)\n', (19278, 19292), True, 'import healpy as hp\n'), ((19323, 19337), 'time.clock', 'timing.clock', ([], {}), '()\n', (19335, 19337), True, 'import time as timing\n'), ((19344, 19357), 'time.time', 'timing.time', ([], {}), '()\n', (19355, 19357), True, 'import time as timing\n'), ((21657, 21678), 'numpy.degrees', 'np.degrees', (['HourAngle'], {}), '(HourAngle)\n', (21667, 21678), True, 'import numpy as np\n'), ((21801, 21815), 'time.clock', 'timing.clock', ([], {}), '()\n', (21813, 21815), True, 'import time as timing\n'), ((21822, 21835), 'time.time', 'timing.time', ([], {}), '()\n', (21833, 21835), True, 'import time as timing\n'), ((23278, 23292), 'time.clock', 'timing.clock', ([], {}), '()\n', (23290, 23292), True, 'import time as timing\n'), ((23299, 23312), 'time.time', 'timing.time', ([], {}), '()\n', (23310, 23312), True, 'import time as timing\n'), ((2100, 2118), 'numpy.sum', 'np.sum', (['(angles < 0)'], {}), '(angles < 0)\n', (2106, 2118), True, 'import numpy as np\n'), ((2244, 2270), 'numpy.sum', 'np.sum', (['(angles < 0)'], {'axis': '(1)'}), '(angles < 0, axis=1)\n', (2250, 2270), True, 'import numpy as np\n'), ((2937, 2946), 'numpy.abs', 'np.abs', (['t'], {}), '(t)\n', (2943, 2946), True, 'import numpy as np\n'), ((3007, 3020), 'numpy.array', 'np.array', (['[t]'], {}), '([t])\n', (3015, 3020), True, 'import numpy as np\n'), ((3127, 3138), 'numpy.floor', 'np.floor', (['h'], {}), '(h)\n', (3135, 3138), True, 'import numpy as np\n'), ((4578, 4593), 'numpy.int', 'np.int', (['(y / 100)'], {}), '(y / 100)\n', (4584, 4593), True, 'import numpy as np\n'), ((8237, 8255), 'numpy.log2', 'np.log2', (['nside_eff'], {}), '(nside_eff)\n', (8244, 8255), True, 'import numpy as np\n'), ((12705, 12724), 'numpy.array', 'np.array', (['LCT_start'], {}), '(LCT_start)\n', (12713, 12724), True, 'import numpy as np\n'), ((12727, 12745), 'numpy.array', 'np.array', (['LCT_step'], {}), '(LCT_step)\n', (12735, 12745), True, 'import numpy as np\n'), ((21319, 21354), 'astropy.time.Time', 'Time', (['JD'], {'format': '"""jd"""', 'location': 'loc'}), "(JD, format='jd', location=loc)\n", (21323, 21354), False, 'from astropy.time import Time\n'), ((21448, 21459), 'numpy.sin', 'np.sin', (['Alt'], {}), '(Alt)\n', (21454, 21459), True, 'import numpy as np\n'), ((21462, 21473), 'numpy.sin', 'np.sin', (['Lat'], {}), '(Lat)\n', (21468, 21473), True, 'import numpy as np\n'), ((21504, 21514), 'numpy.cos', 'np.cos', (['Az'], {}), '(Az)\n', (21510, 21514), True, 'import numpy as np\n'), ((21543, 21554), 'numpy.sin', 'np.sin', (['Alt'], {}), '(Alt)\n', (21549, 21554), True, 'import numpy as np\n'), ((21587, 21598), 'numpy.cos', 'np.cos', (['Dec'], {}), '(Dec)\n', (21593, 21598), True, 'import numpy as np\n'), ((21601, 21612), 'numpy.cos', 'np.cos', (['Lat'], {}), '(Lat)\n', (21607, 21612), True, 'import numpy as np\n'), ((2438, 2449), 'numpy.abs', 'np.abs', (['deg'], {}), '(deg)\n', (2444, 2449), True, 'import numpy as np\n'), ((2969, 2978), 'numpy.abs', 'np.abs', (['t'], {}), '(t)\n', (2975, 2978), True, 'import numpy as np\n'), ((19067, 19091), 'healpy.vec2ang', 'hp.vec2ang', (['fp_pointings'], {}), '(fp_pointings)\n', (19077, 19091), True, 'import healpy as hp\n'), ((21476, 21487), 'numpy.cos', 'np.cos', (['Alt'], {}), '(Alt)\n', (21482, 21487), True, 'import numpy as np\n'), ((21490, 21501), 'numpy.cos', 'np.cos', (['Lat'], {}), '(Lat)\n', (21496, 21501), True, 'import numpy as np\n'), ((21557, 21568), 'numpy.sin', 'np.sin', (['Dec'], {}), '(Dec)\n', (21563, 21568), True, 'import numpy as np\n'), ((21571, 21582), 'numpy.sin', 'np.sin', (['Lat'], {}), '(Lat)\n', (21577, 21582), True, 'import numpy as np\n'), ((3069, 3080), 'numpy.floor', 'np.floor', (['h'], {}), '(h)\n', (3077, 3080), True, 'import numpy as np\n')]
# -*- coding: utf-8 -*- import cv2 from keras.models import load_model import matplotlib.pyplot as plt import numpy as np import os from urllib.request import urlopen import sys ### required - do no delete #def user(): return dict(form=auth()) #def download(): return response.download(request,db) #def call(): return service() ### end requires def index(): images = db().select(db.images.ALL, orderby=db.images.title) form = SQLFORM(db.images) if form.process().accepted: response.flash='URL used' #comments=db(db.images.id==images.id).select() return dict(images=images,form=form) def error(): return dict() def get_image(image): if (image.file!=None): img1 = os.path.join(request.folder, 'uploads', image.file) #response.flash=img1 img=cv2.imread(img1) else: resp = urlopen(image.url) data = np.asarray(bytearray(resp.read()),dtype='uint8') img=cv2.imdecode(data, cv2.IMREAD_COLOR) return img def show(): image=db.images(request.args(0,cast=int)) or redirect(URL('index')) #response.flash = image #image=db(db.images.id==img_id).select() #response.flash = image.file, image.url img = get_image(image) vis,digit_num =mser(img) #response.flash = len(digit_num) Num_de=loadmodel(img) db.images.update_or_insert(db.images.id==image.id,Num_detected=Num_de) #nu = db.images.update(Num_detected=Num_de) return dict(image=image,digit_num=len(digit_num),vis=vis) def download(): return response.download(request,db) def loadmodel(img): width = 17 height = 32 dim = (width, height) #img=cv2.imread('/web2py/applications/images/uploads/images.file.8f89d0198785941b.746573742e706e67.png') vis,digit_num =mser(img) #if digit_num.: #response.flash =digit_num.pop() digit_resize=[] for i in range(len(digit_num)): if(len(digit_num[i])>0): digit_resize.append(cv2.resize(digit_num[i],dim,interpolation = cv2.INTER_AREA)) digit_resize[i]=(digit_resize[i][...,::-1].astype(np.float32))/255 digit_arr2 = np.array(digit_resize) train_model = os.path.join(request.folder, 'private', 'number_model.h5') model = load_model(train_model) pred = model.predict_classes(digit_arr2) print(pred) #pred=0 return pred def mser(cv_image): digit_num = [] #if (len(cv_image)>0): vis = cv_image.copy() gray = cv2.cvtColor(cv_image, cv2.COLOR_BGR2GRAY) #gray = cv2.bilateralFilter(gray, 11, 17, 17) edged = cv2.Canny(gray, 30, 200) mser = cv2.MSER_create() regions, _ = mser.detectRegions(edged) for p in regions: xmax, ymax = np.amax(p, axis=0) xmin, ymin = np.amin(p, axis=0) cv2.rectangle(vis, (xmin,ymin), (xmax,ymax), (0, 255, 0), 1) digit_num.append(vis[ymin:ymax,xmin:xmax]) return vis,digit_num
[ "keras.models.load_model", "cv2.Canny", "numpy.amin", "cv2.cvtColor", "cv2.imdecode", "urllib.request.urlopen", "numpy.amax", "cv2.imread", "cv2.rectangle", "numpy.array", "cv2.MSER_create", "os.path.join", "cv2.resize" ]
[((2111, 2133), 'numpy.array', 'np.array', (['digit_resize'], {}), '(digit_resize)\n', (2119, 2133), True, 'import numpy as np\n'), ((2152, 2210), 'os.path.join', 'os.path.join', (['request.folder', '"""private"""', '"""number_model.h5"""'], {}), "(request.folder, 'private', 'number_model.h5')\n", (2164, 2210), False, 'import os\n'), ((2223, 2246), 'keras.models.load_model', 'load_model', (['train_model'], {}), '(train_model)\n', (2233, 2246), False, 'from keras.models import load_model\n'), ((2440, 2482), 'cv2.cvtColor', 'cv2.cvtColor', (['cv_image', 'cv2.COLOR_BGR2GRAY'], {}), '(cv_image, cv2.COLOR_BGR2GRAY)\n', (2452, 2482), False, 'import cv2\n'), ((2545, 2569), 'cv2.Canny', 'cv2.Canny', (['gray', '(30)', '(200)'], {}), '(gray, 30, 200)\n', (2554, 2569), False, 'import cv2\n'), ((2581, 2598), 'cv2.MSER_create', 'cv2.MSER_create', ([], {}), '()\n', (2596, 2598), False, 'import cv2\n'), ((713, 764), 'os.path.join', 'os.path.join', (['request.folder', '"""uploads"""', 'image.file'], {}), "(request.folder, 'uploads', image.file)\n", (725, 764), False, 'import os\n'), ((806, 822), 'cv2.imread', 'cv2.imread', (['img1'], {}), '(img1)\n', (816, 822), False, 'import cv2\n'), ((848, 866), 'urllib.request.urlopen', 'urlopen', (['image.url'], {}), '(image.url)\n', (855, 866), False, 'from urllib.request import urlopen\n'), ((943, 979), 'cv2.imdecode', 'cv2.imdecode', (['data', 'cv2.IMREAD_COLOR'], {}), '(data, cv2.IMREAD_COLOR)\n', (955, 979), False, 'import cv2\n'), ((2685, 2703), 'numpy.amax', 'np.amax', (['p'], {'axis': '(0)'}), '(p, axis=0)\n', (2692, 2703), True, 'import numpy as np\n'), ((2725, 2743), 'numpy.amin', 'np.amin', (['p'], {'axis': '(0)'}), '(p, axis=0)\n', (2732, 2743), True, 'import numpy as np\n'), ((2752, 2814), 'cv2.rectangle', 'cv2.rectangle', (['vis', '(xmin, ymin)', '(xmax, ymax)', '(0, 255, 0)', '(1)'], {}), '(vis, (xmin, ymin), (xmax, ymax), (0, 255, 0), 1)\n', (2765, 2814), False, 'import cv2\n'), ((1954, 2013), 'cv2.resize', 'cv2.resize', (['digit_num[i]', 'dim'], {'interpolation': 'cv2.INTER_AREA'}), '(digit_num[i], dim, interpolation=cv2.INTER_AREA)\n', (1964, 2013), False, 'import cv2\n')]
import numpy as np import csv import argparse def H(x): '''The Gaussian Hamiltonian x^2 used in this problem''' return x ** 2 def delta_H(x_old, x_new): '''The difference in Hamiltonian''' return H(x_new) - H(x_old) def uniform_step(x, h): '''Returns a new x in the interval of width 2h around the current value''' return x + h * np.random.uniform(-h, h) def metropolis(x, h, beta): '''A single Metropolis update for the Gaussian system''' x_new = uniform_step(x, h) exp_minusbetadeltaH = np.exp(-beta * delta_H(x, x_new)) if exp_minusbetadeltaH > 1: return x_new, 1 elif np.random.random() < exp_minusbetadeltaH: return x_new, 1 else: return x, 0 def run_mc(x, h, beta, num_iterations, output_file): '''Run num_iterations Metropolis updates, and output the data to a file''' with open(output_file, "w") as f: writer = csv.writer(f) writer.writerow(["x", "accept"]) for i in range(num_iterations): x, accept = metropolis(x, h, beta) writer.writerow([x, accept]) def main(): parser = argparse.ArgumentParser(description="Runs Metropolis Monte Carlo") parser.add_argument("x0", type=float, help="Initial value for the state x") parser.add_argument("beta", type=float, help="Inverse temperature beta") parser.add_argument("h", type=float, help="Maximum step size in x") parser.add_argument("num_iterations", type=int, help="Number of steps to use") parser.add_argument("output_file", help="File to output x data to") args = parser.parse_args() run_mc(args.x0, args.h, args.beta, args.num_iterations, args.output_file) if __name__ == '__main__': main()
[ "csv.writer", "numpy.random.uniform", "numpy.random.random", "argparse.ArgumentParser" ]
[((1132, 1198), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""Runs Metropolis Monte Carlo"""'}), "(description='Runs Metropolis Monte Carlo')\n", (1155, 1198), False, 'import argparse\n'), ((922, 935), 'csv.writer', 'csv.writer', (['f'], {}), '(f)\n', (932, 935), False, 'import csv\n'), ((357, 381), 'numpy.random.uniform', 'np.random.uniform', (['(-h)', 'h'], {}), '(-h, h)\n', (374, 381), True, 'import numpy as np\n'), ((638, 656), 'numpy.random.random', 'np.random.random', ([], {}), '()\n', (654, 656), True, 'import numpy as np\n')]
from __future__ import absolute_import, division, print_function import os.path import torch import torch.utils.data as data import numpy as np from torchvision import transforms as vision_transforms from .common import read_image_as_byte, read_calib_into_dict from .common import kitti_crop_image_list, kitti_adjust_intrinsic from .common import intrinsic_scale class KITTI_Raw(data.Dataset): def __init__(self, args, images_root=None, preprocessing_crop=False, crop_size=[370, 1224], num_examples=-1, index_file=None): self._args = args self._seq_len = 1 self._preprocessing_crop = preprocessing_crop self._crop_size = crop_size path_dir = os.path.dirname(os.path.realpath(__file__)) path_index_file = os.path.join(path_dir, index_file) if not os.path.exists(path_index_file): raise ValueError("Index File '%s' not found!", path_index_file) index_file = open(path_index_file, 'r') ## loading image ----------------------------------- if not os.path.isdir(images_root): raise ValueError("Image directory '%s' not found!") filename_list = [line.rstrip().split(' ') for line in index_file.readlines()] self._image_list = [] view1 = 'image_02/data' view2 = 'image_03/data' ext = '.jpg' for item in filename_list: date = item[0][:10] scene = item[0] idx_src = item[1] for ii in range(self._seq_len): idx_tgt = '%.10d' % (int(idx_src) + ii + 1) name_l1 = os.path.join(images_root, date, scene, view1, idx_src) + ext name_r1 = os.path.join(images_root, date, scene, view2, idx_src) + ext if os.path.isfile(name_l1) and os.path.isfile(name_r1): self._image_list.append([name_l1, name_r1]) if num_examples > 0: self._image_list = self._image_list[:num_examples] self._size = len(self._image_list) ## loading calibration matrix self.intrinsic_dict_l = {} self.intrinsic_dict_r = {} self.intrinsic_dict_l, self.intrinsic_dict_r = read_calib_into_dict(path_dir) # ---------------------------------------------------------- # Image resize only # ---------------------------------------------------------- self._resize_to_tensor = vision_transforms.Compose([ vision_transforms.ToPILImage(), vision_transforms.Resize((256, 512)), vision_transforms.transforms.ToTensor() ]) self._to_tensor = vision_transforms.Compose([ vision_transforms.transforms.ToTensor() ]) def __getitem__(self, index): index = index % self._size im_l1_filename = self._image_list[index][0] im_r1_filename = self._image_list[index][1] # read float32 images and flow im_l1_np = read_image_as_byte(im_l1_filename) im_r1_np = read_image_as_byte(im_r1_filename) # example filename basename = os.path.basename(im_l1_filename)[:6] dirname = os.path.dirname(im_l1_filename)[-51:] datename = dirname[:10] k_l1 = torch.from_numpy(self.intrinsic_dict_l[datename]).float() k_r1 = torch.from_numpy(self.intrinsic_dict_r[datename]).float() k_l1_orig = k_l1.clone() h_orig, w_orig, _ = im_l1_np.shape input_im_size = torch.from_numpy(np.array([h_orig, w_orig])).float() # resizing image if self._preprocessing_crop == False: # No Geometric Augmentation, Resizing to 256 x 512 here # resizing input images im_l1 = self._resize_to_tensor(im_l1_np) im_r1 = self._resize_to_tensor(im_r1_np) # resizing intrinsic matrix k_l1 = intrinsic_scale(k_l1, im_l1.size(1) / h_orig, im_l1.size(2) / w_orig) k_r1 = intrinsic_scale(k_r1, im_r1.size(1) / h_orig, im_r1.size(2) / w_orig) else: # For Geometric Augmentation, first croping the images to 370 x 1224 here, # then do the augmentation in augmentation.py # get starting positions crop_height = self._crop_size[0] crop_width = self._crop_size[1] x = np.random.uniform(0, w_orig - crop_width + 1) y = np.random.uniform(0, h_orig - crop_height + 1) crop_info = [int(x), int(y), int(x + crop_width), int(y + crop_height)] # cropping images and adjust intrinsic accordingly im_l1_np, im_r1_np = kitti_crop_image_list([im_l1_np, im_r1_np], crop_info) im_l1 = self._to_tensor(im_l1_np) im_r1 = self._to_tensor(im_r1_np) k_l1, k_r1 = kitti_adjust_intrinsic(k_l1, k_r1, crop_info) # For CamCOnv k_r1_flip = k_r1.clone() k_r1_flip[0, 2] = im_r1.size(2) - k_r1_flip[0, 2] example_dict = { "input_l1": im_l1, "input_r1": im_r1, "index": index, "basename": basename, "datename": datename, "input_k_l1_orig": k_l1_orig, "input_k_l1": k_l1, "input_k_r1": k_r1, "input_k_r1_flip": k_r1_flip, "input_size": input_im_size } return example_dict def __len__(self): return self._size class KITTI_Raw_KittiSplit_Train(KITTI_Raw): def __init__(self, args, root, preprocessing_crop=False, crop_size=[370, 1224], num_examples=-1): super(KITTI_Raw_KittiSplit_Train, self).__init__( args, images_root=root, preprocessing_crop=preprocessing_crop, crop_size=crop_size, num_examples=num_examples, index_file="index_txt/kitti_train.txt") class KITTI_Raw_KittiSplit_Valid(KITTI_Raw): def __init__(self, args, root, preprocessing_crop=False, crop_size=[370, 1224], num_examples=-1): super(KITTI_Raw_KittiSplit_Valid, self).__init__( args, images_root=root, preprocessing_crop=preprocessing_crop, crop_size=crop_size, num_examples=num_examples, index_file="index_txt/kitti_valid.txt")
[ "numpy.random.uniform", "torchvision.transforms.ToPILImage", "torchvision.transforms.transforms.ToTensor", "numpy.array", "torchvision.transforms.Resize", "torch.from_numpy" ]
[((4459, 4504), 'numpy.random.uniform', 'np.random.uniform', (['(0)', '(w_orig - crop_width + 1)'], {}), '(0, w_orig - crop_width + 1)\n', (4476, 4504), True, 'import numpy as np\n'), ((4521, 4567), 'numpy.random.uniform', 'np.random.uniform', (['(0)', '(h_orig - crop_height + 1)'], {}), '(0, h_orig - crop_height + 1)\n', (4538, 4567), True, 'import numpy as np\n'), ((2579, 2609), 'torchvision.transforms.ToPILImage', 'vision_transforms.ToPILImage', ([], {}), '()\n', (2607, 2609), True, 'from torchvision import transforms as vision_transforms\n'), ((2623, 2659), 'torchvision.transforms.Resize', 'vision_transforms.Resize', (['(256, 512)'], {}), '((256, 512))\n', (2647, 2659), True, 'from torchvision import transforms as vision_transforms\n'), ((2673, 2712), 'torchvision.transforms.transforms.ToTensor', 'vision_transforms.transforms.ToTensor', ([], {}), '()\n', (2710, 2712), True, 'from torchvision import transforms as vision_transforms\n'), ((2790, 2829), 'torchvision.transforms.transforms.ToTensor', 'vision_transforms.transforms.ToTensor', ([], {}), '()\n', (2827, 2829), True, 'from torchvision import transforms as vision_transforms\n'), ((3351, 3400), 'torch.from_numpy', 'torch.from_numpy', (['self.intrinsic_dict_l[datename]'], {}), '(self.intrinsic_dict_l[datename])\n', (3367, 3400), False, 'import torch\n'), ((3424, 3473), 'torch.from_numpy', 'torch.from_numpy', (['self.intrinsic_dict_r[datename]'], {}), '(self.intrinsic_dict_r[datename])\n', (3440, 3473), False, 'import torch\n'), ((3608, 3634), 'numpy.array', 'np.array', (['[h_orig, w_orig]'], {}), '([h_orig, w_orig])\n', (3616, 3634), True, 'import numpy as np\n')]
import numpy as np import tensorflow as tf def normalization( input_t, data_or_datalist, name='normalization', err_on_inv_feats=True): if isinstance(data_or_datalist, np.ndarray): datalist = [data_or_datalist] else: datalist = data_or_datalist for data in datalist: assert data.shape[1:] == input_t.shape[1:] assert len(input_t.shape) <= 2 data = np.concatenate(datalist, axis=0) mu = np.mean(data, axis=0, keepdims=True) std = np.std(data, axis=0, keepdims=True) invariant_features = (std == 0) with tf.name_scope(name): if np.any(invariant_features): assert len(input_t.shape) == 2 msg = 'There are invariant features %s!' % \ str(np.where(invariant_features)) if err_on_inv_feats: raise ValueError(msg) else: print(msg) input_t = tf.stack([ input_t[:, i] for i in range(input_t.shape[1]) if not invariant_features[0][i]], axis=1) mu = np.stack([ mu[:, i] for i in range(mu.shape[1]) if not invariant_features[0][i]], axis=1) std = np.stack([ std[:, i] for i in range(std.shape[1]) if not invariant_features[0][i]], axis=1) normalized_t = input_t - tf.constant(mu, dtype=tf.float32, name='mu') assert np.all(std > 0) normalized_t /= tf.constant(std, dtype=tf.float32, name='std') mean_t = tf.reduce_mean(normalized_t) tf.summary.scalar('mean', mean_t, collections=['d0']) tf.summary.scalar('std', tf.sqrt(tf.reduce_mean(tf.square( normalized_t - mean_t))), collections=['d0']) return normalized_t, ~invariant_features def normalization_nd(input_t, data_or_datalist, name='normalization'): if isinstance(data_or_datalist, np.ndarray): datalist = [data_or_datalist] else: datalist = data_or_datalist for data in datalist: assert data.shape[1:] == input_t.shape[1:] assert len(input_t.shape) > 2 data = np.concatenate(datalist, axis=0) mu = np.mean(data, axis=0, keepdims=True) std = np.std(data, axis=0, keepdims=True) invariant_features = (std == 0) std[invariant_features] = 1 with tf.name_scope(name): if np.any(invariant_features): print( 'There are invariant features %s!' % str(np.where(invariant_features))) normalized_t = input_t - tf.constant(mu, dtype=tf.float32, name='mu') assert np.all(std > 0) normalized_t /= tf.constant(std, dtype=tf.float32, name='std') mean_t = tf.reduce_mean(normalized_t) tf.summary.scalar('mean', mean_t, collections=['d0']) tf.summary.scalar('std', tf.sqrt(tf.reduce_mean(tf.square( normalized_t - mean_t))), collections=['d0']) return normalized_t
[ "tensorflow.summary.scalar", "numpy.std", "tensorflow.reduce_mean", "numpy.all", "tensorflow.constant", "numpy.any", "numpy.mean", "numpy.where", "tensorflow.square", "tensorflow.name_scope", "numpy.concatenate" ]
[((401, 433), 'numpy.concatenate', 'np.concatenate', (['datalist'], {'axis': '(0)'}), '(datalist, axis=0)\n', (415, 433), True, 'import numpy as np\n'), ((443, 479), 'numpy.mean', 'np.mean', (['data'], {'axis': '(0)', 'keepdims': '(True)'}), '(data, axis=0, keepdims=True)\n', (450, 479), True, 'import numpy as np\n'), ((490, 525), 'numpy.std', 'np.std', (['data'], {'axis': '(0)', 'keepdims': '(True)'}), '(data, axis=0, keepdims=True)\n', (496, 525), True, 'import numpy as np\n'), ((2170, 2202), 'numpy.concatenate', 'np.concatenate', (['datalist'], {'axis': '(0)'}), '(datalist, axis=0)\n', (2184, 2202), True, 'import numpy as np\n'), ((2212, 2248), 'numpy.mean', 'np.mean', (['data'], {'axis': '(0)', 'keepdims': '(True)'}), '(data, axis=0, keepdims=True)\n', (2219, 2248), True, 'import numpy as np\n'), ((2259, 2294), 'numpy.std', 'np.std', (['data'], {'axis': '(0)', 'keepdims': '(True)'}), '(data, axis=0, keepdims=True)\n', (2265, 2294), True, 'import numpy as np\n'), ((571, 590), 'tensorflow.name_scope', 'tf.name_scope', (['name'], {}), '(name)\n', (584, 590), True, 'import tensorflow as tf\n'), ((603, 629), 'numpy.any', 'np.any', (['invariant_features'], {}), '(invariant_features)\n', (609, 629), True, 'import numpy as np\n'), ((1473, 1488), 'numpy.all', 'np.all', (['(std > 0)'], {}), '(std > 0)\n', (1479, 1488), True, 'import numpy as np\n'), ((1513, 1559), 'tensorflow.constant', 'tf.constant', (['std'], {'dtype': 'tf.float32', 'name': '"""std"""'}), "(std, dtype=tf.float32, name='std')\n", (1524, 1559), True, 'import tensorflow as tf\n'), ((1577, 1605), 'tensorflow.reduce_mean', 'tf.reduce_mean', (['normalized_t'], {}), '(normalized_t)\n', (1591, 1605), True, 'import tensorflow as tf\n'), ((1614, 1667), 'tensorflow.summary.scalar', 'tf.summary.scalar', (['"""mean"""', 'mean_t'], {'collections': "['d0']"}), "('mean', mean_t, collections=['d0'])\n", (1631, 1667), True, 'import tensorflow as tf\n'), ((2372, 2391), 'tensorflow.name_scope', 'tf.name_scope', (['name'], {}), '(name)\n', (2385, 2391), True, 'import tensorflow as tf\n'), ((2404, 2430), 'numpy.any', 'np.any', (['invariant_features'], {}), '(invariant_features)\n', (2410, 2430), True, 'import numpy as np\n'), ((2648, 2663), 'numpy.all', 'np.all', (['(std > 0)'], {}), '(std > 0)\n', (2654, 2663), True, 'import numpy as np\n'), ((2688, 2734), 'tensorflow.constant', 'tf.constant', (['std'], {'dtype': 'tf.float32', 'name': '"""std"""'}), "(std, dtype=tf.float32, name='std')\n", (2699, 2734), True, 'import tensorflow as tf\n'), ((2752, 2780), 'tensorflow.reduce_mean', 'tf.reduce_mean', (['normalized_t'], {}), '(normalized_t)\n', (2766, 2780), True, 'import tensorflow as tf\n'), ((2789, 2842), 'tensorflow.summary.scalar', 'tf.summary.scalar', (['"""mean"""', 'mean_t'], {'collections': "['d0']"}), "('mean', mean_t, collections=['d0'])\n", (2806, 2842), True, 'import tensorflow as tf\n'), ((1413, 1457), 'tensorflow.constant', 'tf.constant', (['mu'], {'dtype': 'tf.float32', 'name': '"""mu"""'}), "(mu, dtype=tf.float32, name='mu')\n", (1424, 1457), True, 'import tensorflow as tf\n'), ((2588, 2632), 'tensorflow.constant', 'tf.constant', (['mu'], {'dtype': 'tf.float32', 'name': '"""mu"""'}), "(mu, dtype=tf.float32, name='mu')\n", (2599, 2632), True, 'import tensorflow as tf\n'), ((751, 779), 'numpy.where', 'np.where', (['invariant_features'], {}), '(invariant_features)\n', (759, 779), True, 'import numpy as np\n'), ((1724, 1756), 'tensorflow.square', 'tf.square', (['(normalized_t - mean_t)'], {}), '(normalized_t - mean_t)\n', (1733, 1756), True, 'import tensorflow as tf\n'), ((2899, 2931), 'tensorflow.square', 'tf.square', (['(normalized_t - mean_t)'], {}), '(normalized_t - mean_t)\n', (2908, 2931), True, 'import tensorflow as tf\n'), ((2524, 2552), 'numpy.where', 'np.where', (['invariant_features'], {}), '(invariant_features)\n', (2532, 2552), True, 'import numpy as np\n')]
import itertools, sys import numpy as np from tf_rl.env.continuous_gridworld.env import GridWorld dense_goals = [(13.0, 8.0), (18.0, 11.0), (20.0, 15.0), (22.0, 19.0)] env = GridWorld(max_episode_len=500, num_rooms=1, action_limit_max=1.0, silent_mode=True, start_position=(8.0, 8.0), goal_position=(22.0, 22.0), goal_reward=+100.0, dense_goals=dense_goals, dense_reward=+5, grid_len=30, plot_path="./logs/plots/RandomAgent/") env.show_casing(file_name="cont_grid_world.png") traj = list() max_timestep = 500_000 global_timestep = 0 flag = False for ep in itertools.count(): state = env.reset() while True: global_timestep += 1 sys.stdout.write("\r TimeStep: {0}".format(str(global_timestep))) sys.stdout.flush() traj.append(state) action = env.action_space.sample() state, reward, done, info = env.step(action) # Same as the freq of eval phase in other algos if global_timestep % 100_000 == 0: flag = True if done: if flag: flag = False env.vis_exploration(traj=np.array(traj), file_name="exploration_random_{}.png".format(global_timestep)) env.vis_trajectory(traj=np.array(traj), file_name="traj_random_{}.png".format(global_timestep)) break if global_timestep > max_timestep: break
[ "numpy.array", "tf_rl.env.continuous_gridworld.env.GridWorld", "sys.stdout.flush", "itertools.count" ]
[((175, 440), 'tf_rl.env.continuous_gridworld.env.GridWorld', 'GridWorld', ([], {'max_episode_len': '(500)', 'num_rooms': '(1)', 'action_limit_max': '(1.0)', 'silent_mode': '(True)', 'start_position': '(8.0, 8.0)', 'goal_position': '(22.0, 22.0)', 'goal_reward': '(+100.0)', 'dense_goals': 'dense_goals', 'dense_reward': '(+5)', 'grid_len': '(30)', 'plot_path': '"""./logs/plots/RandomAgent/"""'}), "(max_episode_len=500, num_rooms=1, action_limit_max=1.0,\n silent_mode=True, start_position=(8.0, 8.0), goal_position=(22.0, 22.0),\n goal_reward=+100.0, dense_goals=dense_goals, dense_reward=+5, grid_len=\n 30, plot_path='./logs/plots/RandomAgent/')\n", (184, 440), False, 'from tf_rl.env.continuous_gridworld.env import GridWorld\n'), ((607, 624), 'itertools.count', 'itertools.count', ([], {}), '()\n', (622, 624), False, 'import itertools, sys\n'), ((777, 795), 'sys.stdout.flush', 'sys.stdout.flush', ([], {}), '()\n', (793, 795), False, 'import itertools, sys\n'), ((1152, 1166), 'numpy.array', 'np.array', (['traj'], {}), '(traj)\n', (1160, 1166), True, 'import numpy as np\n'), ((1271, 1285), 'numpy.array', 'np.array', (['traj'], {}), '(traj)\n', (1279, 1285), True, 'import numpy as np\n')]
import sys import os import time import numpy as np import pyzed.sl as sl import cv2 def main(): path = ["./svo/down/", "./svo/up/", "./svo/obstacle/", "./svo/flatten/", "./svo/test_down/", "./svo/test_up/", "./svo/test_obstacle/", "./svo/test_flatten/", "./svo/test_purity/"] # path = ["./svo/obstacle/", "./svo/flatten/"] for filepath in path: start_read_svo(filepath) def start_read_svo(filepath): for file in os.listdir(filepath): if not file.endswith(".svo"): continue file = filepath + file print(file) print(file.rsplit(".", 1)[0]) input_type = sl.InputType() input_type.set_from_svo_file(file) init = sl.InitParameters(input_t=input_type, svo_real_time_mode=False) init.depth_mode = sl.DEPTH_MODE.ULTRA cam = sl.Camera() status = cam.open(init) if status != sl.ERROR_CODE.SUCCESS: print(repr(status)) exit() runtime = sl.RuntimeParameters() runtime.sensing_mode = sl.SENSING_MODE.FILL # runtime.sensing_mode = sl.SENSING_MODE.STANDARD mat = sl.Mat() key = '' i = 0 print(" Save the current image: s") print(" Quit the video reading: q\n") while key != 113: # for 'q' key err = cam.grab(runtime) if err == sl.ERROR_CODE.SUCCESS: cam.retrieve_image(mat) rgb = mat.get_data() # cv2.imshow("RGB", rgb) depthimg = get_depth_img(cam, mat) # cv2.imshow("Dep", depth) key = cv2.waitKey(1) if i>cam.get_svo_number_of_frames()*0.1\ and i<cam.get_svo_number_of_frames()*0.75: t = str(time.time()).split(".")[0] cv2.imwrite(file.rsplit(".", 1)[0] + "_rgb_" + str(i) + "_" + t + ".png", rgb) cv2.imwrite(file.rsplit(".", 1)[0] + "_depth_" + str(i) + "_" + t + ".jpg", depthimg) i += 1 else: break cv2.destroyAllWindows() print_camera_information(cam) cam.close() print("\nFINISH") def print_camera_information(cam): print() print("Distorsion factor of the right cam before calibration: {0}.".format( cam.get_camera_information().calibration_parameters_raw.right_cam.disto)) print("Distorsion factor of the right cam after calibration: {0}.\n".format( cam.get_camera_information().calibration_parameters.right_cam.disto)) print("Confidence threshold: {0}".format(cam.get_runtime_parameters().confidence_threshold)) print("Depth min and max range values: {0}, {1}".format(cam.get_init_parameters().depth_minimum_distance, cam.get_init_parameters().depth_maximum_distance)) print("Resolution: {0}, {1}.".format(round(cam.get_camera_information().camera_resolution.width, 2), cam.get_camera_information().camera_resolution.height)) print("Camera FPS: {0}".format(cam.get_camera_information().camera_fps)) print("Frame count: {0}.\n".format(cam.get_svo_number_of_frames())) def get_depth_img(cam, mat): cam.retrieve_measure(mat, sl.MEASURE.DEPTH) depth = mat.get_data() depth_img = _distance_to_0_255(cam, depth) return depth_img def _distance_to_0_255(cam, depth_list): min_dis = cam.get_init_parameters().depth_minimum_distance max_dis = cam.get_init_parameters().depth_maximum_distance depth_list = np.nan_to_num(depth_list, posinf=max_dis, neginf=min_dis) depth_list = (depth_list-min_dis)/(max_dis - min_dis)*255 depth_list = np.uint8(depth_list) depth_list = cv2.cvtColor(depth_list,cv2.COLOR_GRAY2BGR) return depth_list if __name__ == "__main__": main()
[ "numpy.uint8", "numpy.nan_to_num", "pyzed.sl.RuntimeParameters", "pyzed.sl.Camera", "cv2.cvtColor", "cv2.waitKey", "time.time", "pyzed.sl.InputType", "pyzed.sl.InitParameters", "pyzed.sl.Mat", "cv2.destroyAllWindows", "os.listdir" ]
[((467, 487), 'os.listdir', 'os.listdir', (['filepath'], {}), '(filepath)\n', (477, 487), False, 'import os\n'), ((3587, 3644), 'numpy.nan_to_num', 'np.nan_to_num', (['depth_list'], {'posinf': 'max_dis', 'neginf': 'min_dis'}), '(depth_list, posinf=max_dis, neginf=min_dis)\n', (3600, 3644), True, 'import numpy as np\n'), ((3724, 3744), 'numpy.uint8', 'np.uint8', (['depth_list'], {}), '(depth_list)\n', (3732, 3744), True, 'import numpy as np\n'), ((3762, 3806), 'cv2.cvtColor', 'cv2.cvtColor', (['depth_list', 'cv2.COLOR_GRAY2BGR'], {}), '(depth_list, cv2.COLOR_GRAY2BGR)\n', (3774, 3806), False, 'import cv2\n'), ((659, 673), 'pyzed.sl.InputType', 'sl.InputType', ([], {}), '()\n', (671, 673), True, 'import pyzed.sl as sl\n'), ((732, 795), 'pyzed.sl.InitParameters', 'sl.InitParameters', ([], {'input_t': 'input_type', 'svo_real_time_mode': '(False)'}), '(input_t=input_type, svo_real_time_mode=False)\n', (749, 795), True, 'import pyzed.sl as sl\n'), ((856, 867), 'pyzed.sl.Camera', 'sl.Camera', ([], {}), '()\n', (865, 867), True, 'import pyzed.sl as sl\n'), ((1014, 1036), 'pyzed.sl.RuntimeParameters', 'sl.RuntimeParameters', ([], {}), '()\n', (1034, 1036), True, 'import pyzed.sl as sl\n'), ((1161, 1169), 'pyzed.sl.Mat', 'sl.Mat', ([], {}), '()\n', (1167, 1169), True, 'import pyzed.sl as sl\n'), ((2121, 2144), 'cv2.destroyAllWindows', 'cv2.destroyAllWindows', ([], {}), '()\n', (2142, 2144), False, 'import cv2\n'), ((1658, 1672), 'cv2.waitKey', 'cv2.waitKey', (['(1)'], {}), '(1)\n', (1669, 1672), False, 'import cv2\n'), ((1818, 1829), 'time.time', 'time.time', ([], {}), '()\n', (1827, 1829), False, 'import time\n')]
# -*- coding: utf-8 -*- ''' Copyright ⓒ 2018 TEAM YOLO Video System Capstone Design Description : Auto CNN train face data set maker ''' import cv2 # OpenCV 라이브러리 #import copy # 깊은 복사하기 위한 라이브러리 (컬러 이미지 저장할 경우) from itertools import chain # 이미지 데이터를 string으로 변환하기 위한 라이브러리 import numpy as np # Matrix 연산 라이브러리 from YOLO_00_constant import * # 코드에 필요한 상수 라이브러리 ## 레이블에 따른 표정상태 반환 ## def label_num_to_str(x): return {0: 'angry', 1: 'disgusted', 2: 'fearful', 3: 'happy(smile)', 4: 'sad', 5: 'surprised', 6: 'neutral'}[x] ## # 키입력에 따른 레이블 반환 ## def label_key_to_num(x): return {ord('0'): 0, ord('1'): 1, ord('2'): 2, ord('3'): 3, ord('4'): 4, ord('5'): 5, ord('6'): 6}.get(x, None) face_cascade = cv2.CascadeClassifier(CASC_FACE_PATH) # Haarcascade 분류 특징 값 (얼굴 정면) eye_cascade = cv2.CascadeClassifier(CASC_EYE_PATH) # Haarcascade 분류 특징 값 (눈) label_num = 6 # 레이블 초기화 : 중립 file_count = 0 # 저장될 파일 index 초기화 dataset_labels = [] # 저장될 Dataset 레이블 리스트 dataset_images = [] # 저장될 Dataset 이미지 리스트 ### 데이터 헤더 저장 과정 ### f = open(join(DATASET_CSV_DIRECTORY,DATASET_CSV_FILENAME_MINE), "w") # data set을 저장할 파일 스트림 연결 f.write("emotion,pixels,Usage\n") # 데이터 헤더 저장 f.close() # 파일 스트림 연결 해제 vidcap = cv2.VideoCapture(0) # 카메라 스트림 연결 # 0: 자체 카메라 1: USB 카메라 # 이미지를 개선하기 위해 사용한 contrast-limited adaptive histogram equlization clahe = cv2.createCLAHE(clipLimit=2.0, tileGridSize=(8,8)) # Contrast를 제한한 필터 생성 ### 얼굴 검출 및 검출된 얼굴 이미지를 CNN 입력 네트워크 data size로 변환하여 csv파일 및 numpy 데이터로 저장 ### while True: # 종료전까지 무한 반복 저장 ret, frame = vidcap.read() # 카메라로 부터 프레임 받아오기 if frame is None: # 받아온 프레임이 존재하지 않을 경우 print("카메라가 존재하지 않거나 동작하지 않습니다!") break # 프로그램 종료 else: # 프레임이 존재 gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) # 컬러 이미지를 흑백으로 변환 (연산량 감소를 위함) histequ_img = clahe.apply(gray) # contrast-limited adaptive histogram equlization 적용 cv2.imshow("Comparison", np.hstack((gray,histequ_img))) # 비교 프레임 출력 gray = histequ_img faces = face_cascade.detectMultiScale(gray, 1.3, 5) # 흑백 이미지 내에서 얼굴 검출 #frame_cr = copy.deepcopy(frame) # 컬러를 저장하기 위해 Draw할 이미지와 저장할 이미지를 따로 복사 (깊은 복사) # 모든 검출된 얼굴을 사각형으로 Boxing for (x,y,w,h) in faces: # 얼굴이 검출된 좌표 [(x,y) : 시작 좌표 / (w,h) : 폭, 높이] cv2.rectangle(frame,(x,y),(x+w,y+h),(255,0,0), 1) # 직사각형으로 얼굴 영역 Draw (파란색) #cropped_face = frame_cr[y:(y + h), x:(x + w)] # 얼굴 영역 Cropping (컬러) cropped_face_gray = gray[y:(y + h), x:(x + w)] # 얼굴 영역 Cropping (흑백) eyes = eye_cascade.detectMultiScale(cropped_face_gray) # 얼굴 내에서 눈 검출 real_eyenum = 0 # 눈 개수 카운트 초기화 # 눈 검출 ROI 설정을 위함 mid_y = int((2*y + h) / 2.) # 얼굴의 중심점 (y축) high_limit_ey = int(y + h * 0.22) # 얼굴 눈 범위 상단 제한 left_limit_ex = int(x + w * 0.15) # 얼굴 눈 범위 좌측 제한 right_limit_ex = int(x + w * 0.85) # 얼굴 눈 범위 우측 제한 # 직사각형으로 눈 ROI 영역 Draw (빨간색) cv2.rectangle(frame,(left_limit_ex,high_limit_ey),(right_limit_ex,mid_y),(0,0,255), 1) # 각 얼굴에 검출된 눈을 사각형으로 Boxing for (ex, ey, ew, eh) in eyes: # 눈이 검출된 좌표 [(x,y) : 시작 좌표 / (w,h) : 폭, 높이] mid_ex = int((2*(x+ex) + ew)/2.) # 눈 영역의 중심 x좌표 mid_ey = int((2*(y+ey) + eh)/2.) # 눈 영역의 중심 y좌표 if mid_y > mid_ey and mid_ey > high_limit_ey : # 얼굴의 중심점과 이마 사이에 있고 (코, 입 등의 오검출 방지) # 주의 : 아래쪽 위치한 픽셀의 좌표가 더 큼! if left_limit_ex < mid_ex and mid_ex < right_limit_ex: # 미간 근처에 있을 경우 (안경 등의 오검출 방지) real_eyenum += 1 # ROI 내의 눈 개수 카운트 cv2.rectangle(frame, (x + ex, y + ey), (x + ex + ew, y + ey + eh), (0, 255, 0), 1) # 직사각형으로 눈 영역 Draw (초록색) if real_eyenum >= 2: ## ROI 내에 객체가 2개 이상 검출된 경우 데이터 저장 수행 ## # Cropping한 얼굴을 Data set 크기에 맞게 resizing resized = cv2.resize(cropped_face_gray, (SIZE_FACE, SIZE_FACE), interpolation=cv2.INTER_CUBIC) # 흑백 #resized = cv2.resize(frame_cr, (SIZE_FACE, SIZE_FACE), interpolation=cv2.INTER_CUBIC) # 컬러 ## 이미지로 데이터 저장 cv2.imshow("Saved Face Image", resized) # 저장되는 얼굴 이미지 출력 cv2.imwrite(join(DATASET_IMG_DIRECTORY,"dataImage%d.jpg") % file_count, resized) # 이미지 .jpg 형식으로 저장 print('Saved dataImage{0}.jpg'.format(file_count)) # 이미지 저장 알림 ## csv 파일로 데이터 저장 f = open(join(DATASET_CSV_DIRECTORY,DATASET_CSV_FILENAME_MINE), "a") # data set에 이어서 저장하기 위해 파일 스트림 연결 image_data = str(list(chain.from_iterable(resized))) # 이미지를 string 형태로 변환 # 레이블, 이미지 데이터, 데이터 유형의 형식으로 string 데이터 생성 data = ','.join([str(label_num),image_data.replace(',',' ').replace('[','').replace(']',''),'Traning\n']) f.write(data) # data 기록 f.close() # 파일 스트림 연결 해제 ## numpy 형태로 데이터 누적 label_onehot = np.zeros(EMOTIONS_NUM) label_onehot[label_num] = 1.0 dataset_labels.append(label_onehot) # 레이블 데이터 누적 dataset_images.append(resized) # 이미지 데이터 누적 file_count+=1 # 파일 index 증가 cv2.imshow("Orignal frame", frame) # 검출된 객체 Boxing된 현재 프레임 출력 key = cv2.waitKey(100) # 0.1초 동안 키입력 대기 (약 0.1초에 한프레임씩 저장) if key & 0xFF == ord('q'): # 'q'를 누를경우 프로그램 종료 break elif key & 0xFF == ord('s') : # 's'를 누를 경우 일시정지 key_lb = cv2.waitKey(0) & 0xFF # 변환할 레이블 선택 입력 key_lb = label_key_to_num(key_lb) # 입력받은 키를 레이블로 변환 if key_lb is not None: # 정상적인 레이블인 경우 label_num = key_lb # 해당 레이블로 저장 데이터 레이블 변경 # 현재 레이블 알림 print("current label: {0}".format(label_num_to_str(label_num))) ## numpy 형태로 데이터 저장 np.save(join(DATASET_NPY_DIRECTORY, DATASET_IMAGES_FILENAME_MINE), dataset_images) np.save(join(DATASET_NPY_DIRECTORY, DATASET_LABELS_FILENAME_MINE), dataset_labels) vidcap.release() # 카메라 스트림 해제 cv2.destroyAllWindows() # 이미지 창 모두 닫기
[ "cv2.cvtColor", "cv2.waitKey", "cv2.imshow", "numpy.zeros", "numpy.hstack", "cv2.VideoCapture", "cv2.rectangle", "cv2.CascadeClassifier", "cv2.createCLAHE", "cv2.destroyAllWindows", "itertools.chain.from_iterable", "cv2.resize" ]
[((762, 799), 'cv2.CascadeClassifier', 'cv2.CascadeClassifier', (['CASC_FACE_PATH'], {}), '(CASC_FACE_PATH)\n', (783, 799), False, 'import cv2\n'), ((848, 884), 'cv2.CascadeClassifier', 'cv2.CascadeClassifier', (['CASC_EYE_PATH'], {}), '(CASC_EYE_PATH)\n', (869, 884), False, 'import cv2\n'), ((1349, 1368), 'cv2.VideoCapture', 'cv2.VideoCapture', (['(0)'], {}), '(0)\n', (1365, 1368), False, 'import cv2\n'), ((1516, 1567), 'cv2.createCLAHE', 'cv2.createCLAHE', ([], {'clipLimit': '(2.0)', 'tileGridSize': '(8, 8)'}), '(clipLimit=2.0, tileGridSize=(8, 8))\n', (1531, 1567), False, 'import cv2\n'), ((6709, 6732), 'cv2.destroyAllWindows', 'cv2.destroyAllWindows', ([], {}), '()\n', (6730, 6732), False, 'import cv2\n'), ((1903, 1942), 'cv2.cvtColor', 'cv2.cvtColor', (['frame', 'cv2.COLOR_BGR2GRAY'], {}), '(frame, cv2.COLOR_BGR2GRAY)\n', (1915, 1942), False, 'import cv2\n'), ((5751, 5785), 'cv2.imshow', 'cv2.imshow', (['"""Orignal frame"""', 'frame'], {}), "('Orignal frame', frame)\n", (5761, 5785), False, 'import cv2\n'), ((5836, 5852), 'cv2.waitKey', 'cv2.waitKey', (['(100)'], {}), '(100)\n', (5847, 5852), False, 'import cv2\n'), ((2138, 2168), 'numpy.hstack', 'np.hstack', (['(gray, histequ_img)'], {}), '((gray, histequ_img))\n', (2147, 2168), True, 'import numpy as np\n'), ((2533, 2593), 'cv2.rectangle', 'cv2.rectangle', (['frame', '(x, y)', '(x + w, y + h)', '(255, 0, 0)', '(1)'], {}), '(frame, (x, y), (x + w, y + h), (255, 0, 0), 1)\n', (2546, 2593), False, 'import cv2\n'), ((3309, 3407), 'cv2.rectangle', 'cv2.rectangle', (['frame', '(left_limit_ex, high_limit_ey)', '(right_limit_ex, mid_y)', '(0, 0, 255)', '(1)'], {}), '(frame, (left_limit_ex, high_limit_ey), (right_limit_ex, mid_y\n ), (0, 0, 255), 1)\n', (3322, 3407), False, 'import cv2\n'), ((4316, 4405), 'cv2.resize', 'cv2.resize', (['cropped_face_gray', '(SIZE_FACE, SIZE_FACE)'], {'interpolation': 'cv2.INTER_CUBIC'}), '(cropped_face_gray, (SIZE_FACE, SIZE_FACE), interpolation=cv2.\n INTER_CUBIC)\n', (4326, 4405), False, 'import cv2\n'), ((4573, 4612), 'cv2.imshow', 'cv2.imshow', (['"""Saved Face Image"""', 'resized'], {}), "('Saved Face Image', resized)\n", (4583, 4612), False, 'import cv2\n'), ((5493, 5515), 'numpy.zeros', 'np.zeros', (['EMOTIONS_NUM'], {}), '(EMOTIONS_NUM)\n', (5501, 5515), True, 'import numpy as np\n'), ((6092, 6106), 'cv2.waitKey', 'cv2.waitKey', (['(0)'], {}), '(0)\n', (6103, 6106), False, 'import cv2\n'), ((4046, 4132), 'cv2.rectangle', 'cv2.rectangle', (['frame', '(x + ex, y + ey)', '(x + ex + ew, y + ey + eh)', '(0, 255, 0)', '(1)'], {}), '(frame, (x + ex, y + ey), (x + ex + ew, y + ey + eh), (0, 255,\n 0), 1)\n', (4059, 4132), False, 'import cv2\n'), ((5097, 5125), 'itertools.chain.from_iterable', 'chain.from_iterable', (['resized'], {}), '(resized)\n', (5116, 5125), False, 'from itertools import chain\n')]
import os import cv2 import numpy as np from scipy.spatial.distance import dice import torch import torch.nn.functional as F import torch.nn as nn # torch.backends.cudnn.benchmark = True import tqdm from dataset.neural_dataset import ValDataset, SequentialDataset from torch.utils.data.dataloader import DataLoader as PytorchDataLoader from utils import heatmap class flip: FLIP_NONE=0 FLIP_LR=1 FLIP_FULL=2 def flip_tensor_lr(batch): columns = batch.data.size()[-1] return batch.index_select(3, torch.LongTensor(list(reversed(range(columns)))).cuda()) def flip_tensor_ud(batch): rows = batch.data.size()[-2] return batch.index_select(2, torch.LongTensor(list(reversed(range(rows)))).cuda()) def to_numpy(batch): if isinstance(batch, tuple): batch = batch[0] return F.sigmoid(batch).data.cpu().numpy() def predict(model, batch, flips=flip.FLIP_NONE): pred1 = model(batch) if flips > flip.FLIP_NONE: pred2 = flip_tensor_lr(model(flip_tensor_lr(batch))) masks = [pred1, pred2] if flips > flip.FLIP_LR: pred3 = flip_tensor_ud(model(flip_tensor_ud(batch))) pred4 = flip_tensor_ud(flip_tensor_lr(model(flip_tensor_ud(flip_tensor_lr(batch))))) masks.extend([pred3, pred4]) new_mask = torch.mean(torch.stack(masks, 0), 0) return to_numpy(new_mask) return to_numpy(pred1) def read_model(weights_path, project, fold): model = nn.DataParallel(torch.load(os.path.join(weights_path, project, 'fold{}_best.pth'.format(fold))).module) model.eval() return model class Evaluator: def __init__(self, config, ds, folds, test=False, flips=0, num_workers=0, border=12): self.config = config self.ds = ds self.folds = folds self.test = test self.flips = flips self.num_workers = num_workers self.full_image = None self.full_mask = None self.current_mask = None self.full_pred = None self.border = border self.folder = config.folder self.prev_name = None self.on_new = False self.show_mask = config.dbg self.need_dice = False self.dice = [] if self.config.save_images: os.makedirs(os.path.join('..', 'results', self.config.folder), exist_ok=True) def visualize(self, show_light=False, show_base=True): dsize = None hmap = heatmap(self.full_pred) if self.full_image is not None and show_light: light_heat = cv2.addWeighted(self.full_image[:,:,:3], 0.6, hmap, 0.4, 0) if dsize: light_heat = cv2.resize(light_heat, (dsize, dsize)) cv2.imshow('light heat', light_heat) if self.full_mask is not None and self.show_mask: light_mask = cv2.addWeighted(self.full_image[:,:,:3], 0.6, cv2.cvtColor(self.full_mask, cv2.COLOR_GRAY2BGR), 0.4, 0) if dsize: light_mask = cv2.resize(light_mask, (dsize, dsize)) cv2.imshow('light mask', light_mask) if self.full_image is not None and show_base: if dsize: cv2.imshow('image', cv2.resize(self.full_image[:,:,:3], (dsize, dsize))) else: cv2.imshow('image', self.full_image[:,:,:3]) if dsize: hmap = cv2.resize(hmap, (dsize, dsize)) cv2.imshow('heatmap', hmap) if self.full_mask is not None and self.show_mask: if dsize: cv2.imshow('mask', cv2.resize(self.full_mask, (dsize, dsize))) else: cv2.imshow('mask', self.full_mask) if show_light or show_base: cv2.waitKey() def predict(self, skip_folds=None): for fold, (train_index, val_index) in enumerate(self.folds): prefix = ('fold' + str(fold) + "_") if self.test else "" if skip_folds is not None: if fold in skip_folds: continue self.prev_name = None ds_cls = ValDataset if not self.test else SequentialDataset val_dataset = ds_cls(self.ds, val_index, stage='test', config=self.config) val_dl = PytorchDataLoader(val_dataset, batch_size=self.config.predict_batch_size, num_workers=self.num_workers, drop_last=False) weights_path = os.path.join(self.config.models_dir, 'albu') model = read_model(weights_path, self.folder, fold) pbar = val_dl if self.config.dbg else tqdm.tqdm(val_dl, total=len(val_dl)) for data in pbar: self.show_mask = 'mask' in data and self.show_mask if 'mask' not in data: self.need_dice = False predicted = self.predict_samples(model, data) self.process_data(predicted, model, data, prefix=prefix) if not self.config.dbg and self.need_dice: pbar.set_postfix(dice="{:.5f}".format(np.mean(self.dice))) if self.config.use_crop: self.on_image_constructed(prefix=prefix) def cut_border(self, image): return image if not self.border else image[self.border:-self.border, self.border:-self.border, ...] def on_image_constructed(self, prefix=""): self.full_pred = self.cut_border(self.full_pred) if self.full_image is not None: self.full_image = self.cut_border(self.full_image) if self.full_mask is not None: self.full_mask = self.cut_border(self.full_mask) if np.any(self.full_pred>.5) or np.any(self.full_mask>=1): d = 1 - dice(self.full_pred.flatten() > .5, self.full_mask.flatten() >= 1) self.dice.append(d) if self.config.dbg: print(self.prev_name, ' dice: ', d) else: return # print(self.prev_name) if self.config.dbg: self.visualize(show_light=True) if self.config.save_images: self.save(self.prev_name, prefix=prefix) def predict_samples(self, model, data): samples = torch.autograd.Variable(data['image'].cuda(), volatile=True) predicted = predict(model, samples, flips=self.flips) return predicted def get_data(self, data): names = data['image_name'] samples = data['image'].numpy() if self.need_dice or self.show_mask: masks = data['mask'].numpy() masks = np.moveaxis(masks, 1, -1) else: masks = None if self.config.dbg: samples = np.moveaxis(samples, 1, -1) else: samples = None return names, samples, masks def save(self, name, prefix=""): raise NotImplementedError def process_data(self, predicted, model, data, prefix=""): raise NotImplementedError
[ "numpy.moveaxis", "torch.stack", "cv2.waitKey", "cv2.cvtColor", "cv2.imshow", "cv2.addWeighted", "numpy.any", "numpy.mean", "torch.nn.functional.sigmoid", "torch.utils.data.dataloader.DataLoader", "utils.heatmap", "os.path.join", "cv2.resize" ]
[((2437, 2460), 'utils.heatmap', 'heatmap', (['self.full_pred'], {}), '(self.full_pred)\n', (2444, 2460), False, 'from utils import heatmap\n'), ((1316, 1337), 'torch.stack', 'torch.stack', (['masks', '(0)'], {}), '(masks, 0)\n', (1327, 1337), False, 'import torch\n'), ((2541, 2602), 'cv2.addWeighted', 'cv2.addWeighted', (['self.full_image[:, :, :3]', '(0.6)', 'hmap', '(0.4)', '(0)'], {}), '(self.full_image[:, :, :3], 0.6, hmap, 0.4, 0)\n', (2556, 2602), False, 'import cv2\n'), ((2703, 2739), 'cv2.imshow', 'cv2.imshow', (['"""light heat"""', 'light_heat'], {}), "('light heat', light_heat)\n", (2713, 2739), False, 'import cv2\n'), ((3420, 3447), 'cv2.imshow', 'cv2.imshow', (['"""heatmap"""', 'hmap'], {}), "('heatmap', hmap)\n", (3430, 3447), False, 'import cv2\n'), ((3744, 3757), 'cv2.waitKey', 'cv2.waitKey', ([], {}), '()\n', (3755, 3757), False, 'import cv2\n'), ((4258, 4382), 'torch.utils.data.dataloader.DataLoader', 'PytorchDataLoader', (['val_dataset'], {'batch_size': 'self.config.predict_batch_size', 'num_workers': 'self.num_workers', 'drop_last': '(False)'}), '(val_dataset, batch_size=self.config.predict_batch_size,\n num_workers=self.num_workers, drop_last=False)\n', (4275, 4382), True, 'from torch.utils.data.dataloader import DataLoader as PytorchDataLoader\n'), ((4406, 4450), 'os.path.join', 'os.path.join', (['self.config.models_dir', '"""albu"""'], {}), "(self.config.models_dir, 'albu')\n", (4418, 4450), False, 'import os\n'), ((6549, 6574), 'numpy.moveaxis', 'np.moveaxis', (['masks', '(1)', '(-1)'], {}), '(masks, 1, -1)\n', (6560, 6574), True, 'import numpy as np\n'), ((6664, 6691), 'numpy.moveaxis', 'np.moveaxis', (['samples', '(1)', '(-1)'], {}), '(samples, 1, -1)\n', (6675, 6691), True, 'import numpy as np\n'), ((2275, 2324), 'os.path.join', 'os.path.join', (['""".."""', '"""results"""', 'self.config.folder'], {}), "('..', 'results', self.config.folder)\n", (2287, 2324), False, 'import os\n'), ((2652, 2690), 'cv2.resize', 'cv2.resize', (['light_heat', '(dsize, dsize)'], {}), '(light_heat, (dsize, dsize))\n', (2662, 2690), False, 'import cv2\n'), ((3049, 3085), 'cv2.imshow', 'cv2.imshow', (['"""light mask"""', 'light_mask'], {}), "('light mask', light_mask)\n", (3059, 3085), False, 'import cv2\n'), ((3285, 3331), 'cv2.imshow', 'cv2.imshow', (['"""image"""', 'self.full_image[:, :, :3]'], {}), "('image', self.full_image[:, :, :3])\n", (3295, 3331), False, 'import cv2\n'), ((3375, 3407), 'cv2.resize', 'cv2.resize', (['hmap', '(dsize, dsize)'], {}), '(hmap, (dsize, dsize))\n', (3385, 3407), False, 'import cv2\n'), ((5615, 5643), 'numpy.any', 'np.any', (['(self.full_pred > 0.5)'], {}), '(self.full_pred > 0.5)\n', (5621, 5643), True, 'import numpy as np\n'), ((5644, 5671), 'numpy.any', 'np.any', (['(self.full_mask >= 1)'], {}), '(self.full_mask >= 1)\n', (5650, 5671), True, 'import numpy as np\n'), ((2877, 2925), 'cv2.cvtColor', 'cv2.cvtColor', (['self.full_mask', 'cv2.COLOR_GRAY2BGR'], {}), '(self.full_mask, cv2.COLOR_GRAY2BGR)\n', (2889, 2925), False, 'import cv2\n'), ((2994, 3032), 'cv2.resize', 'cv2.resize', (['light_mask', '(dsize, dsize)'], {}), '(light_mask, (dsize, dsize))\n', (3004, 3032), False, 'import cv2\n'), ((3198, 3251), 'cv2.resize', 'cv2.resize', (['self.full_image[:, :, :3]', '(dsize, dsize)'], {}), '(self.full_image[:, :, :3], (dsize, dsize))\n', (3208, 3251), False, 'import cv2\n'), ((3661, 3695), 'cv2.imshow', 'cv2.imshow', (['"""mask"""', 'self.full_mask'], {}), "('mask', self.full_mask)\n", (3671, 3695), False, 'import cv2\n'), ((816, 832), 'torch.nn.functional.sigmoid', 'F.sigmoid', (['batch'], {}), '(batch)\n', (825, 832), True, 'import torch.nn.functional as F\n'), ((3575, 3617), 'cv2.resize', 'cv2.resize', (['self.full_mask', '(dsize, dsize)'], {}), '(self.full_mask, (dsize, dsize))\n', (3585, 3617), False, 'import cv2\n'), ((5035, 5053), 'numpy.mean', 'np.mean', (['self.dice'], {}), '(self.dice)\n', (5042, 5053), True, 'import numpy as np\n')]
""" voter.py -------- Implementation of voter model dynamics on a network. author: <NAME> Submitted as part of the 2019 NetSI Collabathon. """ from netrd.dynamics import BaseDynamics import numpy as np import networkx as nx from ..utilities import unweighted class VoterModel(BaseDynamics): """Voter dynamics.""" @unweighted def simulate(self, G, L, noise=None): r"""Simulate voter-model-style dynamics on a network. Nodes are randomly assigned a state in :math:`\{-1, 1\}`; at each time step all nodes asynchronously update by choosing their new state uniformly from their neighbors. Generates an :math:`N \times L` time series. The results dictionary also stores the ground truth network as `'ground_truth'`. Parameters ---------- G (nx.Graph) the input (ground-truth) graph with `N` nodes. L (int) the length of the desired time series. noise (float, str or None) if noise is present, with this probability a node's state will be randomly redrawn from :math:`\{-1, 1\}` independent of its neighbors' states. If 'automatic', set noise to :math:`1/N`. Returns ------- TS (np.ndarray) an :math:`N \times L` array of synthetic time series data. """ N = G.number_of_nodes() if noise is None: noise = 0 elif noise == 'automatic' or noise == 'auto': noise = 1 / N elif not isinstance(noise, (int, float)): raise ValueError("noise must be a number, 'automatic', or None") transitions = nx.to_numpy_array(G) transitions = transitions / np.sum(transitions, axis=0) TS = np.zeros((N, L)) TS[:, 0] = [1 if x < 0.5 else -1 for x in np.random.rand(N)] indices = np.arange(N) for t in range(1, L): np.random.shuffle(indices) TS[:, t] = TS[:, t - 1] for i in indices: TS[i, t] = np.random.choice(TS[:, t], p=transitions[:, i]) if np.random.rand() < noise: TS[i, t] = 1 if np.random.rand() < 0.5 else -1 self.results['ground_truth'] = G self.results['TS'] = TS return TS
[ "numpy.sum", "numpy.random.rand", "numpy.zeros", "numpy.arange", "numpy.random.choice", "networkx.to_numpy_array", "numpy.random.shuffle" ]
[((1687, 1707), 'networkx.to_numpy_array', 'nx.to_numpy_array', (['G'], {}), '(G)\n', (1704, 1707), True, 'import networkx as nx\n'), ((1786, 1802), 'numpy.zeros', 'np.zeros', (['(N, L)'], {}), '((N, L))\n', (1794, 1802), True, 'import numpy as np\n'), ((1890, 1902), 'numpy.arange', 'np.arange', (['N'], {}), '(N)\n', (1899, 1902), True, 'import numpy as np\n'), ((1744, 1771), 'numpy.sum', 'np.sum', (['transitions'], {'axis': '(0)'}), '(transitions, axis=0)\n', (1750, 1771), True, 'import numpy as np\n'), ((1946, 1972), 'numpy.random.shuffle', 'np.random.shuffle', (['indices'], {}), '(indices)\n', (1963, 1972), True, 'import numpy as np\n'), ((1853, 1870), 'numpy.random.rand', 'np.random.rand', (['N'], {}), '(N)\n', (1867, 1870), True, 'import numpy as np\n'), ((2066, 2113), 'numpy.random.choice', 'np.random.choice', (['TS[:, t]'], {'p': 'transitions[:, i]'}), '(TS[:, t], p=transitions[:, i])\n', (2082, 2113), True, 'import numpy as np\n'), ((2133, 2149), 'numpy.random.rand', 'np.random.rand', ([], {}), '()\n', (2147, 2149), True, 'import numpy as np\n'), ((2195, 2211), 'numpy.random.rand', 'np.random.rand', ([], {}), '()\n', (2209, 2211), True, 'import numpy as np\n')]
# Given a matrix of 'raw' double mutant score diffs as from 'characterize_by_mutagenesis.py', # get a matrix reducing the 16 values from each pair of bases tested to 1. # Reduction approach: assume that for independent bases, score of double mutant = sum of single mutants. # approach 0: # get (double mut - sum(single muts)) for the 9 double mutants in the grid; return the one with the greatest absolute value. # approach 1: get cov(true, predicted) for the 9 double mutants # approach 2: get correlation(true, predicted) for the 9 double mutants # approach 3: get L2 norm of true - predicted for the 9 double mutants import sys import os sys.path.append('../seq_design') import seq_evolution sys.path.append('../models') from model_trainer import one_hot_encode import build_design_cfgs import ConfigParser import numpy as np import pandas as pd from get_seq_gradients import parse_fn_in def merge_greatest(grid_in, grid_ref, x_true, y_true): return np.max(grid_in - grid_ref) def merge_cov(grid_in, grid_ref, x_true, y_true): grid_in = np.delete(grid_in, x_true, axis = 0); grid_in = np.delete(grid_in, y_true, axis = 1); grid_in = grid_in.flatten() grid_ref = np.delete(grid_ref, x_true, axis = 0); grid_ref = np.delete(grid_ref, y_true, axis = 1); grid_ref = grid_ref.flatten() return np.cov(grid_in, grid_ref)[0,1] def merge_corr(grid_in, grid_ref, x_true, y_true): grid_in = np.delete(grid_in, x_true, axis = 0); grid_in = np.delete(grid_in, y_true, axis = 1); grid_in = grid_in.flatten() grid_ref = np.delete(grid_ref, x_true, axis = 0); grid_ref = np.delete(grid_ref, y_true, axis = 1); grid_ref = grid_ref.flatten() return np.corrcoef(grid_in, grid_ref)[0,1] def merge_l2(grid_in, grid_ref, x_true, y_true): grid_in = np.delete(grid_in, x_true, axis = 0); grid_in = np.delete(grid_in, y_true, axis = 1); grid_in = grid_in.flatten() grid_ref = np.delete(grid_ref, x_true, axis = 0); grid_ref = np.delete(grid_ref, y_true, axis = 1); grid_ref = grid_ref.flatten() return np.sqrt(np.sum((grid_in - grid_ref)**2)) MERGE_DICT = {0: merge_greatest, 1: merge_cov, 2: merge_corr, 3: merge_l2} def reduce_grid(grid_in, x_true, y_true, merge_fx): grid_ref = np.zeros(grid_in.shape) for i in range(grid_ref.shape[0]): for j in range(grid_ref.shape[1]): grid_ref[i,j] = grid_in[x_true,j] + grid_in[i,y_true] return merge_fx(grid_in, grid_ref, x_true, y_true) def main(seq_in, fn_in, fn_out, merge_fx): seq_in_oh = one_hot_encode(seq_in).squeeze() dat_in = np.loadtxt(fn_in, delimiter = ',') ans = np.zeros(shape = (seq_in_oh.shape[0], seq_in_oh.shape[0])) for i in range(ans.shape[0]): for j in range(ans.shape[1]): grid_in = dat_in[(4*i):(4*(i+1)), (4*j):(4*(j+1))] i_coor = np.where(seq_in_oh[i,:])[0][0] j_coor = np.where(seq_in_oh[j,:])[0][0] ans[i,j] = reduce_grid(grid_in, i_coor, j_coor, merge_fx) np.savetxt(fn_out, ans, delimiter = ',') if __name__ == '__main__': seq_in = 'TACGTAAATAATTAATAGTAGTGACCGGGCCGATAGATGAGTCATTAGGGATTCCGCTCGCCCTGTGTCTGGGTGTTGCGGCATCCGGCATCCAGTAGTGGGTGTAGAATTGTGTGATAGGCATCCAGTGTCTGCATCCCAGCCACACCCCACTTTAGCACTATTTTCACCAGTGCGCCGCTCCCGTTGTCAATGGGTCTACCCCCTGTTTTCCAGGAGGTATATAAAGGAATGGTTTTTCGCGTTATCGATTTATATTATATGTTAATAAAAAATGGTATTTAATTTTTATTTCACCAAGTCCAATTCTCAATTCTCTCATAACTACATTTACTCAATGTCTAAAGGTGAAGAATTATTCAC' fn_in = 'char_mut_0_0_double.csv' fns_out = ('char_mut_0_0_reduced_greatest.csv', 'char_mut_0_0_reduced_cov.csv', 'char_mut_0_0_reduced_corr.csv', 'char_mut_0_0_reduced_l2.csv') merge_id = (0,1,2,3) for (p,q) in zip(fns_out, merge_id): main(seq_in, fn_in, p, MERGE_DICT[q])
[ "sys.path.append", "numpy.sum", "numpy.corrcoef", "numpy.savetxt", "numpy.zeros", "model_trainer.one_hot_encode", "numpy.max", "numpy.where", "numpy.loadtxt", "numpy.cov", "numpy.delete" ]
[((642, 674), 'sys.path.append', 'sys.path.append', (['"""../seq_design"""'], {}), "('../seq_design')\n", (657, 674), False, 'import sys\n'), ((696, 724), 'sys.path.append', 'sys.path.append', (['"""../models"""'], {}), "('../models')\n", (711, 724), False, 'import sys\n'), ((957, 983), 'numpy.max', 'np.max', (['(grid_in - grid_ref)'], {}), '(grid_in - grid_ref)\n', (963, 983), True, 'import numpy as np\n'), ((1047, 1081), 'numpy.delete', 'np.delete', (['grid_in', 'x_true'], {'axis': '(0)'}), '(grid_in, x_true, axis=0)\n', (1056, 1081), True, 'import numpy as np\n'), ((1095, 1129), 'numpy.delete', 'np.delete', (['grid_in', 'y_true'], {'axis': '(1)'}), '(grid_in, y_true, axis=1)\n', (1104, 1129), True, 'import numpy as np\n'), ((1174, 1209), 'numpy.delete', 'np.delete', (['grid_ref', 'x_true'], {'axis': '(0)'}), '(grid_ref, x_true, axis=0)\n', (1183, 1209), True, 'import numpy as np\n'), ((1224, 1259), 'numpy.delete', 'np.delete', (['grid_ref', 'y_true'], {'axis': '(1)'}), '(grid_ref, y_true, axis=1)\n', (1233, 1259), True, 'import numpy as np\n'), ((1397, 1431), 'numpy.delete', 'np.delete', (['grid_in', 'x_true'], {'axis': '(0)'}), '(grid_in, x_true, axis=0)\n', (1406, 1431), True, 'import numpy as np\n'), ((1445, 1479), 'numpy.delete', 'np.delete', (['grid_in', 'y_true'], {'axis': '(1)'}), '(grid_in, y_true, axis=1)\n', (1454, 1479), True, 'import numpy as np\n'), ((1524, 1559), 'numpy.delete', 'np.delete', (['grid_ref', 'x_true'], {'axis': '(0)'}), '(grid_ref, x_true, axis=0)\n', (1533, 1559), True, 'import numpy as np\n'), ((1574, 1609), 'numpy.delete', 'np.delete', (['grid_ref', 'y_true'], {'axis': '(1)'}), '(grid_ref, y_true, axis=1)\n', (1583, 1609), True, 'import numpy as np\n'), ((1750, 1784), 'numpy.delete', 'np.delete', (['grid_in', 'x_true'], {'axis': '(0)'}), '(grid_in, x_true, axis=0)\n', (1759, 1784), True, 'import numpy as np\n'), ((1798, 1832), 'numpy.delete', 'np.delete', (['grid_in', 'y_true'], {'axis': '(1)'}), '(grid_in, y_true, axis=1)\n', (1807, 1832), True, 'import numpy as np\n'), ((1877, 1912), 'numpy.delete', 'np.delete', (['grid_ref', 'x_true'], {'axis': '(0)'}), '(grid_ref, x_true, axis=0)\n', (1886, 1912), True, 'import numpy as np\n'), ((1927, 1962), 'numpy.delete', 'np.delete', (['grid_ref', 'y_true'], {'axis': '(1)'}), '(grid_ref, y_true, axis=1)\n', (1936, 1962), True, 'import numpy as np\n'), ((2188, 2211), 'numpy.zeros', 'np.zeros', (['grid_in.shape'], {}), '(grid_in.shape)\n', (2196, 2211), True, 'import numpy as np\n'), ((2503, 2535), 'numpy.loadtxt', 'np.loadtxt', (['fn_in'], {'delimiter': '""","""'}), "(fn_in, delimiter=',')\n", (2513, 2535), True, 'import numpy as np\n'), ((2546, 2602), 'numpy.zeros', 'np.zeros', ([], {'shape': '(seq_in_oh.shape[0], seq_in_oh.shape[0])'}), '(shape=(seq_in_oh.shape[0], seq_in_oh.shape[0]))\n', (2554, 2602), True, 'import numpy as np\n'), ((2887, 2925), 'numpy.savetxt', 'np.savetxt', (['fn_out', 'ans'], {'delimiter': '""","""'}), "(fn_out, ans, delimiter=',')\n", (2897, 2925), True, 'import numpy as np\n'), ((1302, 1327), 'numpy.cov', 'np.cov', (['grid_in', 'grid_ref'], {}), '(grid_in, grid_ref)\n', (1308, 1327), True, 'import numpy as np\n'), ((1652, 1682), 'numpy.corrcoef', 'np.corrcoef', (['grid_in', 'grid_ref'], {}), '(grid_in, grid_ref)\n', (1663, 1682), True, 'import numpy as np\n'), ((2013, 2046), 'numpy.sum', 'np.sum', (['((grid_in - grid_ref) ** 2)'], {}), '((grid_in - grid_ref) ** 2)\n', (2019, 2046), True, 'import numpy as np\n'), ((2459, 2481), 'model_trainer.one_hot_encode', 'one_hot_encode', (['seq_in'], {}), '(seq_in)\n', (2473, 2481), False, 'from model_trainer import one_hot_encode\n'), ((2743, 2768), 'numpy.where', 'np.where', (['seq_in_oh[i, :]'], {}), '(seq_in_oh[i, :])\n', (2751, 2768), True, 'import numpy as np\n'), ((2789, 2814), 'numpy.where', 'np.where', (['seq_in_oh[j, :]'], {}), '(seq_in_oh[j, :])\n', (2797, 2814), True, 'import numpy as np\n')]
from __future__ import absolute_import from builtins import object import logging import numpy as np import threading import six.moves.queue as queue from relaax.common import profiling from relaax.server.common import session from relaax.common.algorithms.lib import utils from relaax.common.algorithms.lib import observation from .lib.da3c_replay_buffer import DA3CReplayBuffer from . import da3c_config from . import da3c_model logger = logging.getLogger(__name__) profiler = profiling.get_profiler(__name__) M = False # DA3CAgent implements training regime for DA3C algorithm # If exploit on init set to True, agent will run in exploitation regime: # stop updating shared parameters and at the end of every episode load # new policy parameters from PS class Agent(object): def __init__(self, parameter_server, metrics): self.ps = parameter_server self.metrics = metrics self.exploit = False self.session = None self.lstm_zero_state = None self.lstm_state = self.initial_lstm_state = None self.observation = None self.last_action = None self.last_value = None self.last_probs = None self.queue = None self.icm_observation = None self.replay_buffer = None self.terminal = False self.discounted_reward = None self.filter = None self.agent_weights_id = 0 # environment is ready and # waiting for agent to initialize def init(self, exploit=False): self.exploit = exploit model = da3c_model.AgentModel() self.session = session.Session(model) if da3c_config.config.use_lstm: self.lstm_state = self.initial_lstm_state = self.lstm_zero_state = model.lstm_zero_state if da3c_config.config.lstm_type.lower() == 'dilated': self.session.op_lstm_reset_timestep() self.observation = observation.Observation(da3c_config.config.input.history) self.last_action = None self.last_value = None self.last_probs = None if da3c_config.config.hogwild and not da3c_config.config.use_icm: self.queue = queue.Queue(10) threading.Thread(target=self.execute_tasks).start() self.receive_experience() else: self.queue = None if da3c_config.config.use_icm: self.icm_observation = observation.Observation(da3c_config.config.input.history) if da3c_config.config.use_filter: self.filter = utils.ZFilter(da3c_config.config.input.shape) self.replay_buffer = DA3CReplayBuffer(self) return True # Callback methods def begin(self): self.do_task(self.receive_experience) if da3c_config.config.use_lstm: self.initial_lstm_state = self.lstm_state self.get_action_and_value() def end(self, experience): if not self.exploit: self.do_task(lambda: self.send_experience(experience)) @profiler.wrap def reset(self): if da3c_config.config.use_lstm: self.initial_lstm_state = self.lstm_state = self.lstm_zero_state if da3c_config.config.lstm_type.lower() == 'dilated': self.session.op_lstm_reset_timestep() # End callback methods @profiler.wrap def step(self, reward, state, terminal): if da3c_config.config.use_filter and not terminal: state = self.filter(state) if reward is not None: if da3c_config.config.use_icm and not terminal: int_reward = self.get_intrinsic_reward(state) self.metrics.scalar('intrinsic_reward', int_reward) reward += int_reward reward = np.tanh(reward) self.push_experience(reward, terminal) else: if da3c_config.config.use_icm: self.icm_observation.add_state(None) self.icm_observation.add_state(state) if terminal: self.observation.add_state(None) else: assert state is not None self.metrics.histogram('state', state) self.observation.add_state(state) self.terminal = terminal assert self.last_action is None assert self.last_value is None assert self.last_probs is None self.get_action_and_value() @property def experience(self): return self.replay_buffer.experience # environment generated new state and reward # and asking agent for an action for this state @profiler.wrap def update(self, reward, state, terminal): self.check_state_shape(state) # replace empty state with constant one if list(np.asarray(state).shape) == [0]: state = [0] self.step(reward, state, terminal) return self.last_action @staticmethod def check_state_shape(state): if state is None: return expected_shape = list(da3c_config.options.algorithm.input.shape) actual_shape = list(np.asarray(state).shape) if actual_shape != expected_shape: logger.warning('State shape %s does not match to expected one %s.', repr(actual_shape), repr(expected_shape)) ######################### # From batch def execute_tasks(self): while True: task = self.queue.get() task() def do_task(self, f): if self.queue is None: f() else: self.queue.put(f) @profiler.wrap def send_experience(self, experience): self.apply_gradients(self.compute_gradients(experience), experience['reward']) if da3c_config.config.use_icm: self.ps.session.op_icm_apply_gradients(gradients=self.compute_icm_gradients(experience)) @profiler.wrap def receive_experience(self): self.ps.session.op_check_weights() weights, self.agent_weights_id = self.ps.session.op_get_weights() # print('w_id', self.agent_weights_id) if M: for i, w in enumerate(utils.Utils.flatten(weights)): self.metrics.histogram('weight_%d' % i, w) self.session.op_assign_weights(weights=weights) if da3c_config.config.use_icm: self.session.op_icm_assign_weights(weights=self.ps.session.op_icm_get_weights()) def push_experience(self, reward, terminal): assert self.observation.queue is not None assert self.last_action is not None assert self.last_value is not None assert self.last_probs is not None self.replay_buffer.step( terminal, reward=reward, state=self.observation.queue, action=self.last_action, value=self.last_value, probs=self.last_probs ) self.last_action = None self.last_value = None self.last_probs = None def get_action_and_value(self): if self.observation.queue is None: self.last_action = None self.last_value = None self.last_probs = None else: self.last_action, self.last_value = self.get_action_and_value_from_network() assert self.last_action is not None assert self.last_value is not None assert self.last_probs is not None def get_action_and_value_from_network(self): if da3c_config.config.use_lstm: action, value, lstm_state = \ self.session.op_get_action_value_and_lstm_state(state=[self.observation.queue], lstm_state=self.lstm_state, lstm_step=[1]) condition = self.experience is not None and (len(self.experience) == da3c_config.config.batch_size or self.terminal) if not condition: self.lstm_state = lstm_state else: action, value = self.session.op_get_action_and_value(state=[self.observation.queue]) value, = value if len(action) == 1: if M: self.metrics.histogram('action', action) self.last_probs, = action return utils.choose_action_descrete(self.last_probs), value mu, sigma2 = action self.last_probs = mu if M: self.metrics.histogram('mu', mu) self.metrics.histogram('sigma2', sigma2) return utils.choose_action_continuous(mu, sigma2, da3c_config.config.output.action_low, da3c_config.config.output.action_high), value def get_intrinsic_reward(self, state): self.icm_observation.add_state(state) if state is not None: icm_input = [self.observation.queue, self.icm_observation.queue] return self.session.op_get_intrinsic_reward(state=icm_input, probs=[self.last_probs])[0] return 0 def compute_gradients(self, experience): r = 0.0 if self.last_value is not None: r = self.last_value reward = experience['reward'] gamma = da3c_config.config.rewards_gamma # compute discounted rewards self.discounted_reward = utils.discount(np.asarray(reward + [r], dtype=np.float32), gamma)[:-1] # compute advantage wrt rewards and critic values forward_values = np.asarray(experience['value'][1:] + [r]) * gamma rewards = np.asarray(reward) + forward_values - np.asarray(experience['value']) advantage = utils.discount(rewards, gamma * da3c_config.config.gae_lambda, normalize=da3c_config.config.norm_adv) feeds = dict(state=experience['state'], action=experience['action'], advantage=advantage, discounted_reward=self.discounted_reward) if da3c_config.config.use_lstm: feeds.update(dict(lstm_state=self.initial_lstm_state, lstm_step=[len(reward)])) gradients, summaries = self.session.op_compute_gradients_and_summaries(**feeds) self.metrics.summary(summaries) return gradients def compute_icm_gradients(self, experience): states, icm_states = experience['state'], [] for i in range(len(states) - 1): icm_states.extend((states[i], states[i + 1])) icm_states.extend((states[-1], self.icm_observation.queue)) return self.session.op_compute_icm_gradients(state=icm_states, action=experience['action'], probs=experience['probs']) def apply_gradients(self, gradients, rewards): experience_size = len(rewards) if M: for i, g in enumerate(utils.Utils.flatten(gradients)): self.metrics.histogram('gradients_%d' % i, g) # self.ps.session.op_apply_gradients(gradients=gradients, increment=experience_size) self.ps.session.op_submit_gradients(gradients=gradients, step_inc=experience_size, agent_step=self.agent_weights_id) self.ps.session.op_check_weights() self.ps.session.op_add_rewards_to_model_score_routine(reward_sum=sum(rewards), reward_weight=experience_size)
[ "relaax.common.algorithms.lib.utils.discount", "threading.Thread", "relaax.server.common.session.Session", "numpy.tanh", "relaax.common.algorithms.lib.utils.choose_action_continuous", "numpy.asarray", "relaax.common.algorithms.lib.observation.Observation", "relaax.common.algorithms.lib.utils.choose_ac...
[((445, 472), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (462, 472), False, 'import logging\n'), ((484, 516), 'relaax.common.profiling.get_profiler', 'profiling.get_profiler', (['__name__'], {}), '(__name__)\n', (506, 516), False, 'from relaax.common import profiling\n'), ((1601, 1623), 'relaax.server.common.session.Session', 'session.Session', (['model'], {}), '(model)\n', (1616, 1623), False, 'from relaax.server.common import session\n'), ((1913, 1970), 'relaax.common.algorithms.lib.observation.Observation', 'observation.Observation', (['da3c_config.config.input.history'], {}), '(da3c_config.config.input.history)\n', (1936, 1970), False, 'from relaax.common.algorithms.lib import observation\n'), ((9682, 9788), 'relaax.common.algorithms.lib.utils.discount', 'utils.discount', (['rewards', '(gamma * da3c_config.config.gae_lambda)'], {'normalize': 'da3c_config.config.norm_adv'}), '(rewards, gamma * da3c_config.config.gae_lambda, normalize=\n da3c_config.config.norm_adv)\n', (9696, 9788), False, 'from relaax.common.algorithms.lib import utils\n'), ((2164, 2179), 'six.moves.queue.Queue', 'queue.Queue', (['(10)'], {}), '(10)\n', (2175, 2179), True, 'import six.moves.queue as queue\n'), ((2400, 2457), 'relaax.common.algorithms.lib.observation.Observation', 'observation.Observation', (['da3c_config.config.input.history'], {}), '(da3c_config.config.input.history)\n', (2423, 2457), False, 'from relaax.common.algorithms.lib import observation\n'), ((2527, 2572), 'relaax.common.algorithms.lib.utils.ZFilter', 'utils.ZFilter', (['da3c_config.config.input.shape'], {}), '(da3c_config.config.input.shape)\n', (2540, 2572), False, 'from relaax.common.algorithms.lib import utils\n'), ((3741, 3756), 'numpy.tanh', 'np.tanh', (['reward'], {}), '(reward)\n', (3748, 3756), True, 'import numpy as np\n'), ((8586, 8710), 'relaax.common.algorithms.lib.utils.choose_action_continuous', 'utils.choose_action_continuous', (['mu', 'sigma2', 'da3c_config.config.output.action_low', 'da3c_config.config.output.action_high'], {}), '(mu, sigma2, da3c_config.config.output.\n action_low, da3c_config.config.output.action_high)\n', (8616, 8710), False, 'from relaax.common.algorithms.lib import utils\n'), ((9523, 9564), 'numpy.asarray', 'np.asarray', (["(experience['value'][1:] + [r])"], {}), "(experience['value'][1:] + [r])\n", (9533, 9564), True, 'import numpy as np\n'), ((9629, 9660), 'numpy.asarray', 'np.asarray', (["experience['value']"], {}), "(experience['value'])\n", (9639, 9660), True, 'import numpy as np\n'), ((5063, 5080), 'numpy.asarray', 'np.asarray', (['state'], {}), '(state)\n', (5073, 5080), True, 'import numpy as np\n'), ((6107, 6135), 'relaax.common.algorithms.lib.utils.Utils.flatten', 'utils.Utils.flatten', (['weights'], {}), '(weights)\n', (6126, 6135), False, 'from relaax.common.algorithms.lib import utils\n'), ((8349, 8394), 'relaax.common.algorithms.lib.utils.choose_action_descrete', 'utils.choose_action_descrete', (['self.last_probs'], {}), '(self.last_probs)\n', (8377, 8394), False, 'from relaax.common.algorithms.lib import utils\n'), ((9383, 9425), 'numpy.asarray', 'np.asarray', (['(reward + [r])'], {'dtype': 'np.float32'}), '(reward + [r], dtype=np.float32)\n', (9393, 9425), True, 'import numpy as np\n'), ((9591, 9609), 'numpy.asarray', 'np.asarray', (['reward'], {}), '(reward)\n', (9601, 9609), True, 'import numpy as np\n'), ((10910, 10940), 'relaax.common.algorithms.lib.utils.Utils.flatten', 'utils.Utils.flatten', (['gradients'], {}), '(gradients)\n', (10929, 10940), False, 'from relaax.common.algorithms.lib import utils\n'), ((2192, 2235), 'threading.Thread', 'threading.Thread', ([], {'target': 'self.execute_tasks'}), '(target=self.execute_tasks)\n', (2208, 2235), False, 'import threading\n'), ((4732, 4749), 'numpy.asarray', 'np.asarray', (['state'], {}), '(state)\n', (4742, 4749), True, 'import numpy as np\n')]
from cpyMSpec import isotopePattern, InstrumentModel from pyMSpec.pyisocalc import pyisocalc import numpy as np import logging from collections import namedtuple logger = logging.getLogger('engine') ISOTOPIC_PEAK_N = 4 SIGMA_TO_FWHM = 2.3548200450309493 # 2 \sqrt{2 \log 2} class IsocalcWrapper(object): """ Wrapper around pyMSpec.pyisocalc.pyisocalc used for getting theoretical isotope peaks' centroids and profiles for a sum formula. Args ---------- isocalc_config : dict Dictionary representing isotope_generation section of a dataset config file """ def __init__(self, isocalc_config): self.charge = 0 if 'polarity' in isocalc_config['charge']: polarity = isocalc_config['charge']['polarity'] self.charge = (-1 if polarity == '-' else 1) * isocalc_config['charge']['n_charges'] self.sigma = float(isocalc_config['isocalc_sigma']) # self.pts_per_mz = int(isocalc_config['isocalc_pts_per_mz']) @staticmethod def _trim(mzs, ints, k): """ Only keep top k peaks """ int_order = np.argsort(ints)[::-1] mzs = mzs[int_order][:k] ints = ints[int_order][:k] mz_order = np.argsort(mzs) mzs = mzs[mz_order] ints = ints[mz_order] return mzs, ints def ion_centroids(self, sf, adduct): """ Args ---- sf : str adduct: str Returns ------- : list of tuples """ try: pyisocalc.parseSumFormula(sf + adduct) # tests is the sf and adduct compatible iso_pattern = isotopePattern(str(sf + adduct)) iso_pattern.addCharge(int(self.charge)) fwhm = self.sigma * SIGMA_TO_FWHM resolving_power = iso_pattern.masses[0] / fwhm instrument_model = InstrumentModel('tof', resolving_power) centr = iso_pattern.centroids(instrument_model) mzs = np.array(centr.masses) ints = 100. * np.array(centr.intensities) mzs, ints = self._trim(mzs, ints, ISOTOPIC_PEAK_N) return mzs, ints except Exception as e: logger.warning('%s %s - %s', sf, adduct, e) return None, None
[ "cpyMSpec.InstrumentModel", "numpy.argsort", "numpy.array", "pyMSpec.pyisocalc.pyisocalc.parseSumFormula", "logging.getLogger" ]
[((173, 200), 'logging.getLogger', 'logging.getLogger', (['"""engine"""'], {}), "('engine')\n", (190, 200), False, 'import logging\n'), ((1221, 1236), 'numpy.argsort', 'np.argsort', (['mzs'], {}), '(mzs)\n', (1231, 1236), True, 'import numpy as np\n'), ((1111, 1127), 'numpy.argsort', 'np.argsort', (['ints'], {}), '(ints)\n', (1121, 1127), True, 'import numpy as np\n'), ((1532, 1570), 'pyMSpec.pyisocalc.pyisocalc.parseSumFormula', 'pyisocalc.parseSumFormula', (['(sf + adduct)'], {}), '(sf + adduct)\n', (1557, 1570), False, 'from pyMSpec.pyisocalc import pyisocalc\n'), ((1859, 1898), 'cpyMSpec.InstrumentModel', 'InstrumentModel', (['"""tof"""', 'resolving_power'], {}), "('tof', resolving_power)\n", (1874, 1898), False, 'from cpyMSpec import isotopePattern, InstrumentModel\n'), ((1977, 1999), 'numpy.array', 'np.array', (['centr.masses'], {}), '(centr.masses)\n', (1985, 1999), True, 'import numpy as np\n'), ((2026, 2053), 'numpy.array', 'np.array', (['centr.intensities'], {}), '(centr.intensities)\n', (2034, 2053), True, 'import numpy as np\n')]
from matplotlib import cm from tqdm import tqdm from skimage.filters import threshold_otsu from keras.models import load_model import numpy as np import pandas as pd import matplotlib.pyplot as plt import os.path as osp import openslide from pathlib import Path from skimage.filters import threshold_otsu import glob import math # before importing HDFStore, make sure 'tables' is installed by pip3 install tables from pandas import HDFStore from openslide.deepzoom import DeepZoomGenerator from sklearn.model_selection import StratifiedShuffleSplit import cv2 from keras.utils.np_utils import to_categorical output_dir = Path('/home/wli/Downloads/camelyontestonly') import os.path as osp import openslide from pathlib import Path from keras.models import Sequential from keras.layers import Lambda, Dropout from keras.layers.convolutional import Convolution2D, Conv2DTranspose from keras.layers.pooling import MaxPooling2D from keras.models import model_from_json import numpy as np import os import skimage.io as io import skimage.transform as trans import numpy as np from keras.models import * from keras.layers import * from keras.optimizers import * from keras.callbacks import ModelCheckpoint, LearningRateScheduler from keras import backend as keras #BASE_TRUTH_DIR = Path('/home/wli/Downloads/camelyontest/mask') #slide_path = '/home/wli/Downloads/CAMELYON16/training/tumor/' slide_path = '/Volumes/WZL-NIAID-5/New folder (4)/CAMELYON16/training/normal/' #slide_path = '/home/wli/Downloads/CAMELYON16/training/normal/' #slide_path_validation = '/home/wli/Downloads/CAMELYON16/training/tumor/validation/' #slide_path_validation = '/home/wli/Downloads/CAMELYON16/training/normal/validation/' #truth_path = str(BASE_TRUTH_DIR / 'tumor_026_Mask.tif') #slide_paths = list(slide_path) slide_paths = glob.glob(osp.join(slide_path, '*.tif')) #slide_paths_validation = glob.glob(osp.join(slide_path_validation, '*.tif')) #slide_paths = slide_paths + slide_paths_validation #slide_paths = slide_path # slide_paths.sort() #slide = openslide.open_slide(slide_path) def find_patches_from_slide(slide_path, filter_non_tissue=True): """Returns a dataframe of all patches in slide input: slide_path: path to WSI file output: samples: dataframe with the following columns: slide_path: path of slide is_tissue: sample contains tissue is_tumor: truth status of sample tile_loc: coordinates of samples in slide option: base_truth_dir: directory of truth slides option: filter_non_tissue: Remove samples no tissue detected """ #sampletotal = pd.DataFrame([]) #base_truth_dir = Path(BASE_TRUTH_DIR) #anno_path = Path(anno_path) #slide_contains_tumor = osp.basename(slide_paths[i]).startswith('tumor_') print(slide_path) dimensions = [] with openslide.open_slide(slide_path) as slide: dtotal = (slide.dimensions[0] / 224, slide.dimensions[1] / 224) thumbnail = slide.get_thumbnail((dtotal[0], dtotal[1])) thum = np.array(thumbnail) ddtotal = thum.shape dimensions.extend(ddtotal) hsv_image = cv2.cvtColor(thum, cv2.COLOR_BGR2HSV) h, s, v = cv2.split(hsv_image) hthresh = threshold_otsu(h) sthresh = threshold_otsu(s) vthresh = threshold_otsu(v) # be min value for v can be changed later minhsv = np.array([hthresh, sthresh, 70], np.uint8) maxhsv = np.array([180, 255, vthresh], np.uint8) thresh = [minhsv, maxhsv] print(thresh) # extraction the countor for tissue rgbbinary = cv2.inRange(hsv_image, thresh[0], thresh[1]) _, contours, _ = cv2.findContours( rgbbinary, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) bboxtcols = ['xmin', 'xmax', 'ymin', 'ymax'] bboxt = pd.DataFrame(columns=bboxtcols) for c in contours: (x, y, w, h) = cv2.boundingRect(c) bboxt = bboxt.append( pd.Series([x, x+w, y, y+h], index=bboxtcols), ignore_index=True) bboxt = pd.DataFrame(bboxt) xxmin = list(bboxt['xmin'].get_values()) xxmax = list(bboxt['xmax'].get_values()) yymin = list(bboxt['ymin'].get_values()) yymax = list(bboxt['ymax'].get_values()) xxxmin = np.min(xxmin) # xxxmin = math.floor((np.min(xxmin))*224) xxxmax = np.max(xxmax) # xxxmax = math.floor((np.max(xxmax))*224) yyymin = np.min(yymin) # yyymin = math.floor((np.min(yymin))*224) yyymax = np.max(yymax) # yyymax = math.floor((np.max(yymax))*224) dcoord = (xxxmin, xxxmax, yyymin, yyymax) print(dcoord) dimensions.extend(dcoord) # bboxt = math.floor(np.min(xxmin)*256), math.floor(np.max(xxmax)*256), math.floor(np.min(yymin)*256), math.floor(np.max(yymax)*256) samplesnew = pd.DataFrame(pd.DataFrame( np.array(thumbnail.convert('L')))) print(samplesnew) # very critical: y value is for row, x is for column samplesforpred = samplesnew.loc[yyymin:yyymax, xxxmin:xxxmax] #samplesforpred2 = samplesforpred*224 dsample = samplesforpred.shape dimensions.extend(dsample) print(dimensions) np.save('/Users/liw17/Documents/pred_dim/normal/dimensions_%s' % (osp.splitext(osp.basename(slide_paths[i]))[0]), dimensions) # print(samplesforpred) samplesforpredfinal = pd.DataFrame(samplesforpred.stack()) print(samplesforpredfinal) samplesforpredfinal['tile_loc'] = list(samplesforpredfinal.index) samplesforpredfinal.reset_index(inplace=True, drop=True) samplesforpredfinal['slide_path'] = slide_paths[i] print(samplesforpredfinal) samplesforpredfinal.to_pickle( '/Users/liw17/Documents/pred_dim/normal/patch_index_%s.pkl' % (osp.splitext(osp.basename(slide_path))[0])) return samplesforpredfinal i = 0 while i < len(slide_paths): find_patches_from_slide( slide_paths[i], filter_non_tissue=False) i = i+1
[ "pandas.DataFrame", "skimage.filters.threshold_otsu", "os.path.basename", "cv2.cvtColor", "openslide.open_slide", "cv2.inRange", "pathlib.Path", "cv2.split", "numpy.array", "numpy.min", "numpy.max", "pandas.Series", "cv2.boundingRect", "os.path.join", "cv2.findContours" ]
[((622, 666), 'pathlib.Path', 'Path', (['"""/home/wli/Downloads/camelyontestonly"""'], {}), "('/home/wli/Downloads/camelyontestonly')\n", (626, 666), False, 'from pathlib import Path\n'), ((1818, 1847), 'os.path.join', 'osp.join', (['slide_path', '"""*.tif"""'], {}), "(slide_path, '*.tif')\n", (1826, 1847), True, 'import os.path as osp\n'), ((2829, 2861), 'openslide.open_slide', 'openslide.open_slide', (['slide_path'], {}), '(slide_path)\n', (2849, 2861), False, 'import openslide\n'), ((3023, 3042), 'numpy.array', 'np.array', (['thumbnail'], {}), '(thumbnail)\n', (3031, 3042), True, 'import numpy as np\n'), ((3127, 3164), 'cv2.cvtColor', 'cv2.cvtColor', (['thum', 'cv2.COLOR_BGR2HSV'], {}), '(thum, cv2.COLOR_BGR2HSV)\n', (3139, 3164), False, 'import cv2\n'), ((3183, 3203), 'cv2.split', 'cv2.split', (['hsv_image'], {}), '(hsv_image)\n', (3192, 3203), False, 'import cv2\n'), ((3222, 3239), 'skimage.filters.threshold_otsu', 'threshold_otsu', (['h'], {}), '(h)\n', (3236, 3239), False, 'from skimage.filters import threshold_otsu\n'), ((3258, 3275), 'skimage.filters.threshold_otsu', 'threshold_otsu', (['s'], {}), '(s)\n', (3272, 3275), False, 'from skimage.filters import threshold_otsu\n'), ((3294, 3311), 'skimage.filters.threshold_otsu', 'threshold_otsu', (['v'], {}), '(v)\n', (3308, 3311), False, 'from skimage.filters import threshold_otsu\n'), ((3379, 3421), 'numpy.array', 'np.array', (['[hthresh, sthresh, 70]', 'np.uint8'], {}), '([hthresh, sthresh, 70], np.uint8)\n', (3387, 3421), True, 'import numpy as np\n'), ((3439, 3478), 'numpy.array', 'np.array', (['[180, 255, vthresh]', 'np.uint8'], {}), '([180, 255, vthresh], np.uint8)\n', (3447, 3478), True, 'import numpy as np\n'), ((3600, 3644), 'cv2.inRange', 'cv2.inRange', (['hsv_image', 'thresh[0]', 'thresh[1]'], {}), '(hsv_image, thresh[0], thresh[1])\n', (3611, 3644), False, 'import cv2\n'), ((3670, 3741), 'cv2.findContours', 'cv2.findContours', (['rgbbinary', 'cv2.RETR_EXTERNAL', 'cv2.CHAIN_APPROX_SIMPLE'], {}), '(rgbbinary, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)\n', (3686, 3741), False, 'import cv2\n'), ((3824, 3855), 'pandas.DataFrame', 'pd.DataFrame', ([], {'columns': 'bboxtcols'}), '(columns=bboxtcols)\n', (3836, 3855), True, 'import pandas as pd\n'), ((4300, 4313), 'numpy.min', 'np.min', (['xxmin'], {}), '(xxmin)\n', (4306, 4313), True, 'import numpy as np\n'), ((4375, 4388), 'numpy.max', 'np.max', (['xxmax'], {}), '(xxmax)\n', (4381, 4388), True, 'import numpy as np\n'), ((4450, 4463), 'numpy.min', 'np.min', (['yymin'], {}), '(yymin)\n', (4456, 4463), True, 'import numpy as np\n'), ((4525, 4538), 'numpy.max', 'np.max', (['yymax'], {}), '(yymax)\n', (4531, 4538), True, 'import numpy as np\n'), ((3910, 3929), 'cv2.boundingRect', 'cv2.boundingRect', (['c'], {}), '(c)\n', (3926, 3929), False, 'import cv2\n'), ((4065, 4084), 'pandas.DataFrame', 'pd.DataFrame', (['bboxt'], {}), '(bboxt)\n', (4077, 4084), True, 'import pandas as pd\n'), ((3980, 4028), 'pandas.Series', 'pd.Series', (['[x, x + w, y, y + h]'], {'index': 'bboxtcols'}), '([x, x + w, y, y + h], index=bboxtcols)\n', (3989, 4028), True, 'import pandas as pd\n'), ((5334, 5362), 'os.path.basename', 'osp.basename', (['slide_paths[i]'], {}), '(slide_paths[i])\n', (5346, 5362), True, 'import os.path as osp\n'), ((5883, 5907), 'os.path.basename', 'osp.basename', (['slide_path'], {}), '(slide_path)\n', (5895, 5907), True, 'import os.path as osp\n')]
""" A collection of different norms that work on finite-dimensional collections of numbers """ from numpy import array from math import sqrt def l1(x_in): x = array(x_in).flatten() return sum(abs(x)) def l2(x_in): x = array(x_in).flatten() return sqrt(sum(x**2)) def sup(x_in): x = array(x_in).flatten() return max(abs(x)) def hamming(x_in): x = array(x_in).flatten() return sum( ( abs(x) >= 1) * 1 )
[ "numpy.array" ]
[((165, 176), 'numpy.array', 'array', (['x_in'], {}), '(x_in)\n', (170, 176), False, 'from numpy import array\n'), ((233, 244), 'numpy.array', 'array', (['x_in'], {}), '(x_in)\n', (238, 244), False, 'from numpy import array\n'), ((306, 317), 'numpy.array', 'array', (['x_in'], {}), '(x_in)\n', (311, 317), False, 'from numpy import array\n'), ((379, 390), 'numpy.array', 'array', (['x_in'], {}), '(x_in)\n', (384, 390), False, 'from numpy import array\n')]
def addAtoms(input_dat, restart_dat, coords, mol_num, charge): for xyz in coords: restart_dat['mol types'].append( mol_num ) restart_dat['box types'].append( '1' ) # always box 1 restart_dat['coords'].append( [ {'xyz': '%f %f %f\n'%(xyz[0],xyz[1],xyz[2]), 'q': '%f\n'%charge}]) restart_dat['nchain'] = restart_dat['nchain'].replace( restart_dat['nchain'].split()[0], '%i'%(int(restart_dat['nchain'].split()[0])+1) ) input_dat['SIMULATION_BOX']['box1']['mol%s'%mol_num] = '%i'%( int(input_dat['SIMULATION_BOX']['box1']['mol%s'%mol_num]) + 1 ) input_dat['&mc_shared']['nchain'] = restart_dat['nchain'].split()[0] return copy.deepcopy(input_dat), copy.deepcopy(restart_dat) def main(in_dat, res_dat, explic_xyz): si_atoms = [explic_xyz['coords'][i] for i in range(len(explic_xyz['coords'])) if explic_xyz['atoms'][i] == 'Si'] o_atoms = [explic_xyz['coords'][i] for i in range(len(explic_xyz['coords'])) if explic_xyz['atoms'][i] == 'O'] assert len(si_atoms) + len(o_atoms) == len(explic_xyz['coords']), 'Miss counted' in_dat, res_dat = addAtoms(in_dat, res_dat, si_atoms, '2', 1.5) in_dat, res_dat = addAtoms(in_dat, res_dat, o_atoms, '3', -0.75) a,b,c = explic_xyz['box info']['a'], explic_xyz['box info']['b'], explic_xyz['box info']['c'] alpha, gamma, beta = explic_xyz['box info']['alpha'], explic_xyz['box info']['gamma'], explic_xyz['box info']['beta'] if alpha == 90.0 and gamma == 90.0 and beta == 90.0: res_dat['box dimensions']['box1'] = '%f %f %f\n'%(a,b,c) else: alp = alpha/180*np.pi bet = beta/180*np.pi gam = gamma/180*np.pi res_dat['box dimensions']['box1'] = ( ' %f %f %f \n'%(a*np.sin(bet), b*np.sin(alp)*np.cos(gam), 0.) + ' %f %f %f \n'%(0., b*np.sin(alp)*np.sin(gam), 0.) + ' %f %f %f \n'%(a*np.cos(bet), b*np.cos(alp), c) ) old_def = in_dat['SIMULATION_BOX']['box1']['defaults'].split() # '3.5 0.000 0 F F F F' old_def[-4] = 'T' in_dat['SIMULATION_BOX']['box1']['defaults'] = ' '.join(k for k in old_def) return in_dat, res_dat from MCFlow.file_formatting import reader, writer import copy import numpy as np if __name__ == '__main__': import argparse, os parser = argparse.ArgumentParser(description='add explicit to unit cell') parser.add_argument('-f','--file',type=str) parser.add_argument('-lmn','--vectors',type=int,nargs='+',default=[2,2,3]) parser.add_argument('-i','--input',default='fort.4') parser.add_argument('-r','--restart',default='fort.77') args = vars(parser.parse_args()) base_dir = os.getcwd() + '/' data = reader.PDB(args['file']) input_data = reader.read_fort4('%s%s'%(base_dir,args['input'])) nmolty, nbox = (int(input_data['&mc_shared']['nmolty']), int(input_data['&mc_shared']['nbox'])) restart_data = reader.read_restart('%s%s'%(base_dir,args['restart']),nmolty, nbox) input_data, restart_data = main(input_data, restart_data, data) writer.write_fort4(input_data,'fort.4.new') writer.write_restart(restart_data,'fort.77.new')
[ "copy.deepcopy", "argparse.ArgumentParser", "MCFlow.file_formatting.reader.PDB", "os.getcwd", "MCFlow.file_formatting.writer.write_fort4", "MCFlow.file_formatting.reader.read_restart", "MCFlow.file_formatting.reader.read_fort4", "MCFlow.file_formatting.writer.write_restart", "numpy.cos", "numpy.si...
[((2368, 2432), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""add explicit to unit cell"""'}), "(description='add explicit to unit cell')\n", (2391, 2432), False, 'import argparse, os\n'), ((2760, 2784), 'MCFlow.file_formatting.reader.PDB', 'reader.PDB', (["args['file']"], {}), "(args['file'])\n", (2770, 2784), False, 'from MCFlow.file_formatting import reader, writer\n'), ((2802, 2855), 'MCFlow.file_formatting.reader.read_fort4', 'reader.read_fort4', (["('%s%s' % (base_dir, args['input']))"], {}), "('%s%s' % (base_dir, args['input']))\n", (2819, 2855), False, 'from MCFlow.file_formatting import reader, writer\n'), ((2988, 3059), 'MCFlow.file_formatting.reader.read_restart', 'reader.read_restart', (["('%s%s' % (base_dir, args['restart']))", 'nmolty', 'nbox'], {}), "('%s%s' % (base_dir, args['restart']), nmolty, nbox)\n", (3007, 3059), False, 'from MCFlow.file_formatting import reader, writer\n'), ((3128, 3172), 'MCFlow.file_formatting.writer.write_fort4', 'writer.write_fort4', (['input_data', '"""fort.4.new"""'], {}), "(input_data, 'fort.4.new')\n", (3146, 3172), False, 'from MCFlow.file_formatting import reader, writer\n'), ((3176, 3225), 'MCFlow.file_formatting.writer.write_restart', 'writer.write_restart', (['restart_data', '"""fort.77.new"""'], {}), "(restart_data, 'fort.77.new')\n", (3196, 3225), False, 'from MCFlow.file_formatting import reader, writer\n'), ((743, 767), 'copy.deepcopy', 'copy.deepcopy', (['input_dat'], {}), '(input_dat)\n', (756, 767), False, 'import copy\n'), ((769, 795), 'copy.deepcopy', 'copy.deepcopy', (['restart_dat'], {}), '(restart_dat)\n', (782, 795), False, 'import copy\n'), ((2731, 2742), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (2740, 2742), False, 'import argparse, os\n'), ((1943, 1954), 'numpy.cos', 'np.cos', (['bet'], {}), '(bet)\n', (1949, 1954), True, 'import numpy as np\n'), ((1958, 1969), 'numpy.cos', 'np.cos', (['alp'], {}), '(alp)\n', (1964, 1969), True, 'import numpy as np\n'), ((1806, 1817), 'numpy.sin', 'np.sin', (['bet'], {}), '(bet)\n', (1812, 1817), True, 'import numpy as np\n'), ((1833, 1844), 'numpy.cos', 'np.cos', (['gam'], {}), '(gam)\n', (1839, 1844), True, 'import numpy as np\n'), ((1896, 1907), 'numpy.sin', 'np.sin', (['gam'], {}), '(gam)\n', (1902, 1907), True, 'import numpy as np\n'), ((1821, 1832), 'numpy.sin', 'np.sin', (['alp'], {}), '(alp)\n', (1827, 1832), True, 'import numpy as np\n'), ((1884, 1895), 'numpy.sin', 'np.sin', (['alp'], {}), '(alp)\n', (1890, 1895), True, 'import numpy as np\n')]
import numpy as np from sklearn.ensemble import BaggingClassifier from brew.base import Ensemble from brew.combination.combiner import Combiner import sklearn from .base import PoolGenerator class Bagging(PoolGenerator): def __init__(self, base_classifier=None, n_classifiers=100, combination_rule='majority_vote'): self.base_classifier = base_classifier self.n_classifiers = n_classifiers self.ensemble = None self.combiner = Combiner(rule=combination_rule) def fit(self, X, y): self.ensemble = Ensemble() for _ in range(self.n_classifiers): # bootstrap idx = np.random.choice(X.shape[0], X.shape[0], replace=True) data, target = X[idx, :], y[idx] classifier = sklearn.base.clone(self.base_classifier) classifier.fit(data, target) self.ensemble.add(classifier) return def predict(self, X): out = self.ensemble.output(X) return self.combiner.combine(out) class BaggingSK(PoolGenerator): """" This class should not be used, use brew.generation.bagging.Bagging instead. """ def __init__(self, base_classifier=None, n_classifiers=100, combination_rule='majority_vote'): self.base_classifier = base_classifier self.n_classifiers = n_classifiers # using the sklearn implementation of bagging for now self.sk_bagging = BaggingClassifier(base_estimator=base_classifier, n_estimators=n_classifiers, max_samples=1.0, max_features=1.0) self.ensemble = Ensemble() self.combiner = Combiner(rule=combination_rule) def fit(self, X, y): self.sk_bagging.fit(X, y) self.ensemble.add_classifiers(self.sk_bagging.estimators_) # self.classes_ = set(y) def predict(self, X): out = self.ensemble.output(X) return self.combiner.combine(out)
[ "sklearn.ensemble.BaggingClassifier", "brew.combination.combiner.Combiner", "brew.base.Ensemble", "numpy.random.choice", "sklearn.base.clone" ]
[((520, 551), 'brew.combination.combiner.Combiner', 'Combiner', ([], {'rule': 'combination_rule'}), '(rule=combination_rule)\n', (528, 551), False, 'from brew.combination.combiner import Combiner\n'), ((602, 612), 'brew.base.Ensemble', 'Ensemble', ([], {}), '()\n', (610, 612), False, 'from brew.base import Ensemble\n'), ((1536, 1653), 'sklearn.ensemble.BaggingClassifier', 'BaggingClassifier', ([], {'base_estimator': 'base_classifier', 'n_estimators': 'n_classifiers', 'max_samples': '(1.0)', 'max_features': '(1.0)'}), '(base_estimator=base_classifier, n_estimators=\n n_classifiers, max_samples=1.0, max_features=1.0)\n', (1553, 1653), False, 'from sklearn.ensemble import BaggingClassifier\n'), ((1806, 1816), 'brew.base.Ensemble', 'Ensemble', ([], {}), '()\n', (1814, 1816), False, 'from brew.base import Ensemble\n'), ((1841, 1872), 'brew.combination.combiner.Combiner', 'Combiner', ([], {'rule': 'combination_rule'}), '(rule=combination_rule)\n', (1849, 1872), False, 'from brew.combination.combiner import Combiner\n'), ((700, 754), 'numpy.random.choice', 'np.random.choice', (['X.shape[0]', 'X.shape[0]'], {'replace': '(True)'}), '(X.shape[0], X.shape[0], replace=True)\n', (716, 754), True, 'import numpy as np\n'), ((826, 866), 'sklearn.base.clone', 'sklearn.base.clone', (['self.base_classifier'], {}), '(self.base_classifier)\n', (844, 866), False, 'import sklearn\n')]
from LMmodel.tf2_trm import Transformer import logging import numpy as np from utils.text_featurizers import TextFeaturizer import os logging.basicConfig(level=logging.DEBUG, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s') class LM(): def __init__(self,config): self.config=config self.vocab_featurizer = TextFeaturizer(config['lm_vocab']) self.word_featurizer = TextFeaturizer(config['lm_word']) self.model_config=self.config['model_config'] self.model_config.update({'input_vocab_size':self.vocab_featurizer.num_classes,'target_vocab_size':self.word_featurizer.num_classes}) def load_model(self,training=True): self.model = Transformer(**self.model_config) try: if not training: self.model._build() self.load_checkpoint() except: logging.info('lm loading model failed.') self.model.start_id=self.word_featurizer.start self.model.end_id=self.word_featurizer.stop def convert_to_pb(self, export_path): import tensorflow as tf self.model.inference(np.ones([1,10],'int32')) concrete_func = self.model.inference.get_concrete_function() tf.saved_model.save(self.model, export_path, signatures=concrete_func) def load_checkpoint(self, ): """Load checkpoint.""" self.checkpoint_dir = os.path.join(self.config['running_config']["outdir"], "checkpoints") files = os.listdir(self.checkpoint_dir) files.sort(key=lambda x: int(x.split('_')[-1].replace('.h5', ''))) self.model.load_weights(os.path.join(self.checkpoint_dir, files[-1])) def encode(self,word,token): x=[token.start] for i in word: x.append(token.token_to_index[i]) x.append(token.stop) return np.array(x)[np.newaxis,:] def decode(self,out,token): de=[] for i in out[1:]: de.append(token.index_to_token[i]) return de def predict(self,pins): x=self.encode(pins,self.vocab_featurizer) result=self.model.inference(x) return result
[ "logging.basicConfig", "numpy.ones", "LMmodel.tf2_trm.Transformer", "tensorflow.saved_model.save", "utils.text_featurizers.TextFeaturizer", "numpy.array", "logging.info", "os.path.join", "os.listdir" ]
[((139, 247), 'logging.basicConfig', 'logging.basicConfig', ([], {'level': 'logging.DEBUG', 'format': '"""%(asctime)s - %(name)s - %(levelname)s - %(message)s"""'}), "(level=logging.DEBUG, format=\n '%(asctime)s - %(name)s - %(levelname)s - %(message)s')\n", (158, 247), False, 'import logging\n'), ((349, 383), 'utils.text_featurizers.TextFeaturizer', 'TextFeaturizer', (["config['lm_vocab']"], {}), "(config['lm_vocab'])\n", (363, 383), False, 'from utils.text_featurizers import TextFeaturizer\n'), ((416, 449), 'utils.text_featurizers.TextFeaturizer', 'TextFeaturizer', (["config['lm_word']"], {}), "(config['lm_word'])\n", (430, 449), False, 'from utils.text_featurizers import TextFeaturizer\n'), ((713, 745), 'LMmodel.tf2_trm.Transformer', 'Transformer', ([], {}), '(**self.model_config)\n', (724, 745), False, 'from LMmodel.tf2_trm import Transformer\n'), ((1263, 1333), 'tensorflow.saved_model.save', 'tf.saved_model.save', (['self.model', 'export_path'], {'signatures': 'concrete_func'}), '(self.model, export_path, signatures=concrete_func)\n', (1282, 1333), True, 'import tensorflow as tf\n'), ((1433, 1501), 'os.path.join', 'os.path.join', (["self.config['running_config']['outdir']", '"""checkpoints"""'], {}), "(self.config['running_config']['outdir'], 'checkpoints')\n", (1445, 1501), False, 'import os\n'), ((1519, 1550), 'os.listdir', 'os.listdir', (['self.checkpoint_dir'], {}), '(self.checkpoint_dir)\n', (1529, 1550), False, 'import os\n'), ((1157, 1182), 'numpy.ones', 'np.ones', (['[1, 10]', '"""int32"""'], {}), "([1, 10], 'int32')\n", (1164, 1182), True, 'import numpy as np\n'), ((1660, 1704), 'os.path.join', 'os.path.join', (['self.checkpoint_dir', 'files[-1]'], {}), '(self.checkpoint_dir, files[-1])\n', (1672, 1704), False, 'import os\n'), ((1882, 1893), 'numpy.array', 'np.array', (['x'], {}), '(x)\n', (1890, 1893), True, 'import numpy as np\n'), ((899, 939), 'logging.info', 'logging.info', (['"""lm loading model failed."""'], {}), "('lm loading model failed.')\n", (911, 939), False, 'import logging\n')]
# Fraud detection models # Call the functions with data, parameters and the hitlist. # The hitlist will be returned, extended with results of the model import numpy as np import numpy.random as rn import pandas as pd import matplotlib.pyplot as plt import datetime as dt import pickle, os, time, sys, itertools, string rn.seed(42) ###################################################################### def cost_per_member(data, params, hitlist): """ This model compares the cost per member. There are three options for the grouping of providers, as defined in params['Grouping']: - Overall (not advised) - By known specialism, indicated by column with the grouping keyword, default='Prov_specialism' - By determined specialism. The model "billing_pattern" will be run in clustering mode For determining outliers there are also three options, as defined in params['Outlier definition']: - Above 90th percentile - Above 95th percentile - Statistical outlier (upper limit = Q3 + 1.5 (Q3-Q1)) A version of the hitlist with the new results appended is returned. """ option_group = params['Grouping'] option_outlier = params['Outlier definition'] if option_group == 'By determined peer group': # Groups need to be determined piv_proc = pd.pivot_table(data, values='Paid_amt', index='Provider_ID', columns='Procedure_code', aggfunc='sum') piv_proc.replace(np.nan, 0, inplace=True) fractional_proc = piv_proc.div(piv_proc.sum(axis=1), axis=0) from sklearn.decomposition import PCA pca=PCA() manifolds = pca.fit_transform(fractional_proc)[:,:3] from sklearn.cluster import DBSCAN from sklearn.preprocessing import StandardScaler X = StandardScaler().fit_transform(manifolds) results = DBSCAN().fit(X) #This is one label per provider, in order, so I have to join these to the dataframe tojoin = pd.DataFrame({'IDs':piv_proc.index, 'refgroup':results.labels_}) data = data.merge(tojoin, how='left', left_on='Provider_ID', right_on='IDs') elif option_group == 'Overall': data['refgroup'] = np.zeros(len(data.index)) elif option_group == 'Per specialism': data['refgroup'] = data.Prov_specialism else: print("The option for reference groups is not recognized! Overall is used.") refgroup = np.zeros(len(data.index)) data['refgroup'] = refgroup refgroups = np.unique(data.refgroup) if option_outlier == 'Above 90th percentile': percentile = 90 elif option_outlier == 'Above 95th percentile': percentile = 95 elif option_outlier == 'Statistical outlier': pass # Outside upper inner fence = q3+ 1.5*(q3-q1) else: print("Not yet implemented!") outliers = [] score = [] money = [] # plt.subplots_adjust(hspace=0.000) number_of_subplots=len(refgroups) maxval = 0 minval = 1e9 for iref, ref in enumerate(refgroups): if ref == -1 and option_group == 'By determined peer group': continue # These are outliers determined by DBSCAN thisgroup = data[data.refgroup == ref] prov_pat = thisgroup.groupby(['Provider_ID', 'Member_ID']) cost_all_patients = pd.DataFrame(prov_pat.Paid_amt.sum()) cost_all_patients.reset_index(inplace=True) per_prov = cost_all_patients.groupby('Provider_ID') cost_per_member = per_prov.Paid_amt.mean() number_patients = per_prov.Paid_amt.count() if cost_per_member.max() > maxval: maxval = cost_per_member.max() if cost_per_member.min() < minval: minval = cost_per_member.min() if option_group == 'Per specialism': plabel = str('Reference group ')+str(ref) elif option_group == 'By determined peer group': plabel = str('Reference group'+str(ref+1)) elif option_group == 'Overall': plabel = '' else: plabel = '' if option_outlier in ['Above 90th percentile', 'Above 95th percentile']: limval = np.percentile(cost_per_member, percentile) elif option_outlier == 'Statistical outlier': q1, q3 = np.percentile(cost_per_member, [25, 75]) limval = q3 + 1.5 * (q3-q1) else: print("Outlier option not yet implemented!", option_outlier, "Using 90th percentile") limval = np.percentile(cost_per_member, 90) median = np.median(cost_per_member) toomuch = cost_per_member[cost_per_member > limval] scoring_entities = toomuch.index outliers.extend(list(scoring_entities)) score.extend(list((toomuch - limval) / np.abs(limval - median))) npats = number_patients[scoring_entities].values money.extend(list((toomuch-limval)*npats)) # Add those numbers to the hitlist with the model name in it too. hl_add = pd.DataFrame({'Provider_ID':outliers, 'Score':score, 'Monetary':money, 'Model': ['Costs per patient']*len(score), 'Weight':[params['Weight']]*len(score) }) hitlist = hitlist.append(hl_add, sort=True) return hitlist ###################################################################### def billing_pattern(data, params, hitlist): """ In this model, outliers from the general billing pattern (see below) are flagged, based on how far away from the nearest cluster they are. The pattern is defined as the fraction of money billed for different procedures. This multi-dimensional space is reduced to three dimensions. In that 3D space, a DBSCAN cluster finder is used on the standardized locations, so the same density threshold for clusters can be used, no matter the values of input parameters. No monetary loss is defined, as it is not at all clear how this would be defined. """ # Parameters are passed for consistency, in this version it runs without any user-defined parameters. # Create a pivot table with amounts per procedure code for all providers, then normalize piv_proc = pd.pivot_table(data, values='Paid_amt', index='Provider_ID', columns='Procedure_code', aggfunc='sum') piv_proc.replace(np.nan, 0, inplace=True) fractional_proc = piv_proc.div(piv_proc.sum(axis=1), axis=0) # Create a lookup for the specialism prov_spec = data.loc[:,['Provider_ID', 'Prov_specialism']].drop_duplicates() prov_spec.set_index('Provider_ID', inplace=True) specs = np.array(prov_spec.values) # Use PCA to be able to select three main axes. from sklearn.decomposition import PCA pca=PCA() pcas = pca.fit_transform(fractional_proc) # Scale all axes to zero mean, unit stdev and do a density scan. from sklearn.preprocessing import StandardScaler from sklearn.cluster import DBSCAN X = StandardScaler().fit_transform(pcas[:,:3]) scanner = DBSCAN(eps=0.5) results = scanner.fit(X) # Select outliers and compute scores # Compute, for all outliers, the distance to the nearest cluster center and normalize by stdev of that cluster. labels = results.labels_ nclusters = len(np.unique(labels)) - (1 if -1 in labels else 0) # Calculate cluster centers and sizes center = np.zeros([nclusters, 4]) for iclus in range(nclusters): coords = np.array(pcas[labels == iclus]) center[iclus, :3] = np.array([np.mean(coords[:,0]), np.mean(coords[:,1]), np.mean(coords[:,2])]) center[iclus, 3] = np.sqrt(np.std(coords[:,0])**2 + np.std(coords[:,1])**2 + np.std(coords[:,2])**2 ) out_pcas = pcas[labels == -1][:,:3] ids = piv_proc.index[labels == -1] outliers = list(ids) score = [] money = [] for pca in out_pcas: distsq = np.zeros(nclusters) for iclus in range(nclusters): distsq[iclus] = np.sum((np.array(pca) - np.array(center[iclus, :3]))**2) score.append(np.sqrt(np.min(distsq)) / (3*center[np.argmin(distsq), 3])) money.append(0) hl_add = pd.DataFrame({'Provider_ID':outliers, 'Score':score, 'Monetary':money, 'Model': ['Billing pattern']*len(score), 'Weight':[params['Weight']]*len(score)}) hitlist = hitlist.append(hl_add, sort=True) return hitlist ###################################################################### def weekends_holidays(data, params, hitlist): """ Treatments on weekends and holidays are flagged. There is one parameter to rule this model: the choice to flag everybody who did so, or to flag people who do so significantly more often than others. Score is defined as treatments on the fraction of treatments on weekends and holidays, divided by the average of that over everybody who was flagged. Monetary loss is the sum of billed amounts on weekend days and holidays for those who are flagged. In case only the ones with too many such treatments are flagged, it's multiplied by the fraction of treatments that was over the limit. """ holidays = [dt.datetime(2016, 1, 1).date(), dt.datetime(2016, 12, 25).date(), dt.datetime(2016, 8, 10).date(), dt.datetime(2016, 11, 25).date()] data['holiday'] = [1 if (day.weekday() > 4 or day in holidays) else 0 for day in data.Treatment_date] data['holiday_money'] = data.holiday * data.Paid_amt per_prov = data.groupby('Provider_ID') n_treats = per_prov.holiday.count() n_holiday = per_prov.holiday.sum() money_holiday = per_prov.holiday_money.sum() frac_holiday = n_holiday / n_treats suspects = pd.concat([n_treats, n_holiday, money_holiday, frac_holiday], axis=1) suspects.columns=['n_treats', 'n_holiday', 'money_holiday', 'frac_holiday'] suspects = suspects[suspects.n_holiday > 0] average_f = suspects.frac_holiday.mean() std_f = suspects.frac_holiday.std() if params['Flag'] == 'too many': suspects = suspects[suspects.frac_holiday > (average_f + 2*std_f)] corr_frac = suspects.frac_holiday - (average_f + 2*std_f) score = list(suspects.frac_holiday / suspects.frac_holiday.mean()) money = list(suspects.money_holiday * (1 if params['Flag'] == 'all' else corr_frac)) outliers = list(suspects.index) hl_add = pd.DataFrame({'Provider_ID':outliers, 'Score':score, 'Monetary':money, 'Model': ['Treatments on holidays and weekends']*len(score), 'Weight':[params['Weight']]*len(score)}) hitlist = hitlist.append(hl_add, sort=True) return hitlist ###################################################################### def rising_revenue(data, params, hitlist): """ This detection model checks if there are any signs of significantly rising activity/revenue, throughout the period of activity. Both gradually rising, as well as step functions in activity will be detected through the comparison of regression models of cumulative revenue over time. With steady activity, cumulative revenue should be linear with time, with the revenue per unit time as slope. With a steadily rising revenue, the cure will be more parabola like, and a linear regression is likely to result in too low an average revenue per unit time. A step function in activity results in a different slope before and after the step and in case of a rising revenue, this will again look a little parabola-like and result in too low an averge revenue per unit time if estimated with linear regression. Both will also result in a low goodness-of-fit for a linear relation. As a good proxy, the average slope of the cumulative revenue is compared to the total one. The distribution of the ratios of the two is roughly normal. Everything above 2 sigma deviation is flagged, and the score is equal to the dev in stds - maximum allowed deviation (2std). """ # Revenue per month, per provider data['month'] = [d.month for d in data.Treatment_date] perprovpermonth = data.groupby(['Provider_ID', 'month']) revpermonth = perprovpermonth.Paid_amt.sum() cumrev = revpermonth.groupby(level=[0]).cumsum().reset_index() cumrev['slopes'] = cumrev.Paid_amt / cumrev.month av_slope = cumrev.groupby('Provider_ID').slopes.mean() rpm = revpermonth.reset_index() perprov = rpm.groupby('Provider_ID') tot_money = perprov.Paid_amt.sum() / 12 stds = ((tot_money / av_slope)-1) / np.std(tot_money / av_slope) maxstd = 2 stds = stds[stds.values > maxstd] - maxstd hl_add = pd.DataFrame({'Provider_ID':stds.index, 'Score':stds.values, 'Monetary':[0]*len(stds), 'Model': ['Rising revenue']*len(stds), 'Weight':[params['Weight']]*len(stds)}) hitlist = hitlist.append(hl_add, sort=True) return hitlist ###################################################################### def seasonality(data, params, hitlist): """ In summer, patients go on holidays, so there is a trend that fewer patients are treated in July and August, which is (partly) made up by them showing up in September and/or October. This trend is visible in the overall data, with all ehalythcare providers included. This model checks if every provider with enough volume shows this behavior too (so a larger deviation is allowed for those with smaller volume, to correct for Poisson noise in the treatment dates). """ # Revenue per 2 months, per provider data['qmonth'] = [np.floor((d.month - 1)/2) for d in data.Treatment_date] perprovpermonth = data.groupby(['Provider_ID', 'qmonth']) revpermonth = perprovpermonth.Paid_amt.sum().reset_index() uncertainty = (np.sqrt(perprovpermonth.Paid_amt.count()) / (perprovpermonth.Paid_amt.count())).reset_index() uncertainty.rename(columns={'Paid_amt':'uncertainty'}, inplace=True) #Normalize over everyone to find total fracs in all qmonths fracs = (data.groupby('qmonth').Paid_amt.sum() / np.sum(data.Paid_amt)).reset_index() # Same thing per provider, including a measure of uncertainty, based on volume revperprov = data.groupby('Provider_ID').Paid_amt.sum().reset_index() revs = pd.merge(revpermonth, revperprov, left_on='Provider_ID', right_on='Provider_ID', how='left') revs['fracprov'] = revs.Paid_amt_x / revs.Paid_amt_y withun = revs.merge(uncertainty, left_on=['Provider_ID', 'qmonth'], right_on=['Provider_ID', 'qmonth'], how='left') allnumbers = withun.merge(fracs, left_on='qmonth', right_on='qmonth', how='left') allnumbers.rename(columns={'Paid_amt':'totfrac'}, inplace=True) allnumbers['deviation'] = ((allnumbers.fracprov - allnumbers.totfrac) / allnumbers.totfrac) / allnumbers.uncertainty scores = abs(allnumbers.groupby('Provider_ID').deviation.mean()) - 1 scores = scores[scores.values > 0] hl_add = pd.DataFrame({'Provider_ID':scores.index, 'Score':scores.values, 'Monetary':[0]*len(scores), 'Model': ['Seasonality']*len(scores), 'Weight':[params['Weight']]*len(scores)}) hitlist = hitlist.append(hl_add, sort=True) return hitlist ###################################################################### def combination_codes(data, params, hitlist): """ Codes I1 and H1 should not appear together """ combinlines = pd.concat( [data[(data.Procedure_code == "I1")], data[(data.Procedure_code == "H1")]]) combinlines.sort_values(["Provider_ID", "Member_ID", "Treatment_date"], inplace=True) per_visit = combinlines.groupby(["Provider_ID", "Member_ID", "Treatment_date"]) nlines = per_visit.Procedure_code.nunique() nl = pd.DataFrame(nlines).reset_index() per_prov = nl.groupby('Provider_ID') ncombis = per_prov.Procedure_code.sum() - per_prov.Procedure_code.count() ncombis = ncombis[ncombis.values > 0] # Scores such that median = 1, monetary loss is H1 prize per doucle line. mednumber = ncombis.median() ids = ncombis.index score = [p/mednumber for p in ncombis.values] money = [34 * p for p in ncombis.values] # Make the monetary loss equal to the rate for H1: 34. hl_add = pd.DataFrame({'Provider_ID':ids, 'Score':score, 'Monetary':money, 'Model': ['Combination codes']*len(score), 'Weight':[params['Weight']]*len(score)}) hitlist = hitlist.append(hl_add, sort=True) return hitlist ###################################################################### def fraction_expensive(data, params, hitlist): """ An outlier detection is performed on the fraction of expensive versus cheap versions of the same procedure (encoded as A1 vs A2, for example). User specified options are: - determined per specialism or overall - Statistical outliers in the sample, or every provider above 90th percentile is flagged - Outliers are determined in number of cheap vs expensive treatments, or in revenue in cheap vs expensive versions. Scores depend on severity of outlier, monetary losses are undefined if outliers are sought in number of treatments and are defined as the fraction of the expensive revenue that is outside the accepted range. """ # Parameter in settings, per specialism or overall grouping = params['Grouping'] #'per_specialism' or 'overall' if grouping == 'overall': data['Specialism'] = [1 for d in data.Prov_specialism] elif grouping == 'per_specialism': data['Specialism'] = [d for d in data.Prov_specialism] # Parameter in settings: ratio in numbers or in price ratio = params['Ratio'] # options: 'number' or 'price' # Parameter in settings: statistical outlier or above 90th percentile outlier = params['Outlier'] # options: 'statistical' or 'percentile' data['procedure_group'] = [d[0] for d in data.Procedure_code] data['price_group'] = ['Expensive' if float(d[1]) > 1 else 'Cheap' for d in data.Procedure_code] pergroup = data.groupby(['Specialism', 'Provider_ID', 'procedure_group', 'price_group']) if ratio == 'number': quantity = pergroup.Paid_amt.count() elif ratio == 'price': quantity = pergroup.Paid_amt.sum() qs = pd.DataFrame(quantity).reset_index() pivot = pd.pivot_table(qs, index=['Specialism', 'Provider_ID', 'procedure_group'], columns=['price_group'], values='Paid_amt').reset_index() perprov = pivot.groupby(['Specialism', 'Provider_ID']) totcheap = pd.DataFrame(perprov.Cheap.sum()) totexp = pd.DataFrame(perprov.Expensive.sum()) totals = pd.merge(totcheap, totexp, left_index=True, right_index=True).reset_index() totals['frac_exp'] = [(d[1]/(d[0]+d[1])) for d in zip(totals.Cheap, totals.Expensive)] for spec in np.unique(totals.Specialism): thisspec = totals[((totals.Specialism == spec) & (totals.frac_exp > -1))] if outlier == 'statistical': q1, q3 = np.percentile(thisspec.frac_exp, [25, 75]) limval = q3 + 1.5 * (q3-q1) elif outlier == 'percentile': limval = np.percentile(thisspec.frac_exp, 90) else: print("Unknown outlier definition") outliers = thisspec[thisspec.frac_exp > limval] outliers['score'] = (outliers.frac_exp - limval) / np.median(outliers.frac_exp - limval) if ratio == 'number': outliers['money'] = np.zeros(len(outliers.score)) elif ratio == 'price': outliers['money'] = [(d[0]-limval)*d[1] for d in zip(outliers.frac_exp, outliers.Expensive)] hl_add = pd.DataFrame({'Provider_ID':outliers.Provider_ID, 'Score':outliers.score, 'Monetary':outliers.money, 'Model': ['Fraction expensive treatments']*len(outliers.score), 'Weight':[params['Weight']]*len(outliers.score)}) hitlist = hitlist.append(hl_add, sort=True) return hitlist ###################################################################### def freely_billed(data, params, hitlist): """ An outlier detection is performed on billed rate per freely billable procedure. User specified options are: - determined per specialism or overall - Statistical outliers in the sample, or every provider above 90th percentile is flagged - Outliers are determined over all frely billable procedures combined, or per procedure group (indicated by first letter of procedure code) Scores depend on severity of outlier, monetary losses are defined as the difference in revenue between the real value, and what it would be if all freely billed procedures had on average the value that is determined to be the maximum acceptable, from the data. """ grouping = params['Grouping'] # options: 'overall' or 'per_specialism' if grouping == 'overall': data['Specialism'] = [1 for d in data.Prov_specialism] elif grouping == 'per_specialism': data['Specialism'] = [d for d in data.Prov_specialism] group_codes = params['Group_codes'] # options: 'per_procedure', 'overall' outlier = params['Outlier'] # options: 'statistical', 'percentile' # Procedures with free rates: C, F, I data['proc_group'] = [d[0] for d in data.Procedure_code] freerates = data[data.proc_group.isin(['C', 'F', 'I'] ) ] if group_codes == 'overall': freerates['proc_group'] = ['X'] * len(freerates.proc_group) for thisgroup in np.unique(freerates.proc_group): for thisspec in np.unique(freerates.Prov_specialism): subset = freerates[((freerates.proc_group == thisgroup) & (freerates.Prov_specialism == thisspec))] perprov = subset.groupby('Provider_ID') meanrate = pd.DataFrame(perprov.Paid_amt.mean()) totalmoney = pd.DataFrame(perprov.Paid_amt.sum()) results = pd.merge(meanrate, totalmoney, left_index=True, right_index=True) if outlier == 'statistical': q1, q3 = np.percentile(results.Paid_amt_x, [25, 75]) limval = q3 + 1.5 * (q3-q1) elif outlier == 'percentile': limval = np.percentile(results.Paid_amt_x, 90) else: print("Unknown outlier definition") outliers = results[results.Paid_amt_x > limval] outliers['score'] = (outliers.Paid_amt_x - limval) / np.median(outliers.Paid_amt_x - limval) outliers['money'] = [d[1]-(d[1]/d[0]*limval) for d in zip(outliers.Paid_amt_x, outliers.Paid_amt_y)] # print(outliers) hl_add = pd.DataFrame({'Provider_ID':outliers.index, 'Score':outliers.score, 'Monetary':outliers.money, 'Model': ['Rate per freely billed procedure']*len(outliers.score), 'Weight':[params['Weight']]*len(outliers.score)}) hitlist = hitlist.append(hl_add, sort=True) return hitlist ###################################################################### def periodic_often(data, params, hitlist): """ Periodic treatments (code BX) should be done once or twice a year. Catch providers who have done more than that to some patients. """ maxnumber = params['maxnumber'] data['p_group'] = [b[0] for b in data.Procedure_code] data_B = data[data.p_group == 'B'] per_patient = data_B.groupby(['Provider_ID', 'Member_ID']) n_t = per_patient.Treatment_date.nunique() hits = pd.DataFrame(n_t[n_t.values > maxnumber] - maxnumber) hits.reset_index(inplace=True) per_prov = hits.groupby('Provider_ID') nh = per_prov.Treatment_date.sum() med = nh.median() scores = list(nh / med) ids = list(nh.index) money = nh.values * 23 # 23 is the rate for B1 hl_add = pd.DataFrame({'Provider_ID':ids, 'Score':scores, 'Monetary':money, 'Model': ['Periodic treatment too often']*len(scores), 'Weight':[params['Weight']]*len(scores)}) hitlist = hitlist.append(hl_add, sort=True) return hitlist if __name__ == "__main__": print("No tests implemented.")
[ "numpy.random.seed", "pandas.pivot_table", "sklearn.preprocessing.StandardScaler", "numpy.sum", "numpy.abs", "numpy.floor", "numpy.argmin", "numpy.mean", "sklearn.cluster.DBSCAN", "numpy.unique", "pandas.DataFrame", "numpy.std", "pandas.merge", "pandas.concat", "numpy.median", "datetim...
[((322, 333), 'numpy.random.seed', 'rn.seed', (['(42)'], {}), '(42)\n', (329, 333), True, 'import numpy.random as rn\n'), ((2386, 2410), 'numpy.unique', 'np.unique', (['data.refgroup'], {}), '(data.refgroup)\n', (2395, 2410), True, 'import numpy as np\n'), ((5655, 5761), 'pandas.pivot_table', 'pd.pivot_table', (['data'], {'values': '"""Paid_amt"""', 'index': '"""Provider_ID"""', 'columns': '"""Procedure_code"""', 'aggfunc': '"""sum"""'}), "(data, values='Paid_amt', index='Provider_ID', columns=\n 'Procedure_code', aggfunc='sum')\n", (5669, 5761), True, 'import pandas as pd\n'), ((6040, 6066), 'numpy.array', 'np.array', (['prov_spec.values'], {}), '(prov_spec.values)\n', (6048, 6066), True, 'import numpy as np\n'), ((6161, 6166), 'sklearn.decomposition.PCA', 'PCA', ([], {}), '()\n', (6164, 6166), False, 'from sklearn.decomposition import PCA\n'), ((6422, 6437), 'sklearn.cluster.DBSCAN', 'DBSCAN', ([], {'eps': '(0.5)'}), '(eps=0.5)\n', (6428, 6437), False, 'from sklearn.cluster import DBSCAN\n'), ((6758, 6782), 'numpy.zeros', 'np.zeros', (['[nclusters, 4]'], {}), '([nclusters, 4])\n', (6766, 6782), True, 'import numpy as np\n'), ((8965, 9034), 'pandas.concat', 'pd.concat', (['[n_treats, n_holiday, money_holiday, frac_holiday]'], {'axis': '(1)'}), '([n_treats, n_holiday, money_holiday, frac_holiday], axis=1)\n', (8974, 9034), True, 'import pandas as pd\n'), ((13315, 13412), 'pandas.merge', 'pd.merge', (['revpermonth', 'revperprov'], {'left_on': '"""Provider_ID"""', 'right_on': '"""Provider_ID"""', 'how': '"""left"""'}), "(revpermonth, revperprov, left_on='Provider_ID', right_on=\n 'Provider_ID', how='left')\n", (13323, 13412), True, 'import pandas as pd\n'), ((14396, 14481), 'pandas.concat', 'pd.concat', (["[data[data.Procedure_code == 'I1'], data[data.Procedure_code == 'H1']]"], {}), "([data[data.Procedure_code == 'I1'], data[data.Procedure_code ==\n 'H1']])\n", (14405, 14481), True, 'import pandas as pd\n'), ((17656, 17684), 'numpy.unique', 'np.unique', (['totals.Specialism'], {}), '(totals.Specialism)\n', (17665, 17684), True, 'import numpy as np\n'), ((20124, 20155), 'numpy.unique', 'np.unique', (['freerates.proc_group'], {}), '(freerates.proc_group)\n', (20133, 20155), True, 'import numpy as np\n'), ((21898, 21951), 'pandas.DataFrame', 'pd.DataFrame', (['(n_t[n_t.values > maxnumber] - maxnumber)'], {}), '(n_t[n_t.values > maxnumber] - maxnumber)\n', (21910, 21951), True, 'import pandas as pd\n'), ((1268, 1374), 'pandas.pivot_table', 'pd.pivot_table', (['data'], {'values': '"""Paid_amt"""', 'index': '"""Provider_ID"""', 'columns': '"""Procedure_code"""', 'aggfunc': '"""sum"""'}), "(data, values='Paid_amt', index='Provider_ID', columns=\n 'Procedure_code', aggfunc='sum')\n", (1282, 1374), True, 'import pandas as pd\n'), ((1541, 1546), 'sklearn.decomposition.PCA', 'PCA', ([], {}), '()\n', (1544, 1546), False, 'from sklearn.decomposition import PCA\n'), ((1896, 1962), 'pandas.DataFrame', 'pd.DataFrame', (["{'IDs': piv_proc.index, 'refgroup': results.labels_}"], {}), "({'IDs': piv_proc.index, 'refgroup': results.labels_})\n", (1908, 1962), True, 'import pandas as pd\n'), ((4139, 4165), 'numpy.median', 'np.median', (['cost_per_member'], {}), '(cost_per_member)\n', (4148, 4165), True, 'import numpy as np\n'), ((6827, 6858), 'numpy.array', 'np.array', (['pcas[labels == iclus]'], {}), '(pcas[labels == iclus])\n', (6835, 6858), True, 'import numpy as np\n'), ((7222, 7241), 'numpy.zeros', 'np.zeros', (['nclusters'], {}), '(nclusters)\n', (7230, 7241), True, 'import numpy as np\n'), ((11661, 11689), 'numpy.std', 'np.std', (['(tot_money / av_slope)'], {}), '(tot_money / av_slope)\n', (11667, 11689), True, 'import numpy as np\n'), ((12650, 12677), 'numpy.floor', 'np.floor', (['((d.month - 1) / 2)'], {}), '((d.month - 1) / 2)\n', (12658, 12677), True, 'import numpy as np\n'), ((20175, 20211), 'numpy.unique', 'np.unique', (['freerates.Prov_specialism'], {}), '(freerates.Prov_specialism)\n', (20184, 20211), True, 'import numpy as np\n'), ((3795, 3837), 'numpy.percentile', 'np.percentile', (['cost_per_member', 'percentile'], {}), '(cost_per_member, percentile)\n', (3808, 3837), True, 'import numpy as np\n'), ((6368, 6384), 'sklearn.preprocessing.StandardScaler', 'StandardScaler', ([], {}), '()\n', (6382, 6384), False, 'from sklearn.preprocessing import StandardScaler\n'), ((6660, 6677), 'numpy.unique', 'np.unique', (['labels'], {}), '(labels)\n', (6669, 6677), True, 'import numpy as np\n'), ((14704, 14724), 'pandas.DataFrame', 'pd.DataFrame', (['nlines'], {}), '(nlines)\n', (14716, 14724), True, 'import pandas as pd\n'), ((17111, 17133), 'pandas.DataFrame', 'pd.DataFrame', (['quantity'], {}), '(quantity)\n', (17123, 17133), True, 'import pandas as pd\n'), ((17158, 17280), 'pandas.pivot_table', 'pd.pivot_table', (['qs'], {'index': "['Specialism', 'Provider_ID', 'procedure_group']", 'columns': "['price_group']", 'values': '"""Paid_amt"""'}), "(qs, index=['Specialism', 'Provider_ID', 'procedure_group'],\n columns=['price_group'], values='Paid_amt')\n", (17172, 17280), True, 'import pandas as pd\n'), ((17478, 17539), 'pandas.merge', 'pd.merge', (['totcheap', 'totexp'], {'left_index': '(True)', 'right_index': '(True)'}), '(totcheap, totexp, left_index=True, right_index=True)\n', (17486, 17539), True, 'import pandas as pd\n'), ((17805, 17847), 'numpy.percentile', 'np.percentile', (['thisspec.frac_exp', '[25, 75]'], {}), '(thisspec.frac_exp, [25, 75])\n', (17818, 17847), True, 'import numpy as np\n'), ((18107, 18144), 'numpy.median', 'np.median', (['(outliers.frac_exp - limval)'], {}), '(outliers.frac_exp - limval)\n', (18116, 18144), True, 'import numpy as np\n'), ((20479, 20544), 'pandas.merge', 'pd.merge', (['meanrate', 'totalmoney'], {'left_index': '(True)', 'right_index': '(True)'}), '(meanrate, totalmoney, left_index=True, right_index=True)\n', (20487, 20544), True, 'import pandas as pd\n'), ((1714, 1730), 'sklearn.preprocessing.StandardScaler', 'StandardScaler', ([], {}), '()\n', (1728, 1730), False, 'from sklearn.preprocessing import StandardScaler\n'), ((1771, 1779), 'sklearn.cluster.DBSCAN', 'DBSCAN', ([], {}), '()\n', (1777, 1779), False, 'from sklearn.cluster import DBSCAN\n'), ((3901, 3941), 'numpy.percentile', 'np.percentile', (['cost_per_member', '[25, 75]'], {}), '(cost_per_member, [25, 75])\n', (3914, 3941), True, 'import numpy as np\n'), ((4092, 4126), 'numpy.percentile', 'np.percentile', (['cost_per_member', '(90)'], {}), '(cost_per_member, 90)\n', (4105, 4126), True, 'import numpy as np\n'), ((6891, 6912), 'numpy.mean', 'np.mean', (['coords[:, 0]'], {}), '(coords[:, 0])\n', (6898, 6912), True, 'import numpy as np\n'), ((6913, 6934), 'numpy.mean', 'np.mean', (['coords[:, 1]'], {}), '(coords[:, 1])\n', (6920, 6934), True, 'import numpy as np\n'), ((6935, 6956), 'numpy.mean', 'np.mean', (['coords[:, 2]'], {}), '(coords[:, 2])\n', (6942, 6956), True, 'import numpy as np\n'), ((8421, 8444), 'datetime.datetime', 'dt.datetime', (['(2016)', '(1)', '(1)'], {}), '(2016, 1, 1)\n', (8432, 8444), True, 'import datetime as dt\n'), ((8467, 8492), 'datetime.datetime', 'dt.datetime', (['(2016)', '(12)', '(25)'], {}), '(2016, 12, 25)\n', (8478, 8492), True, 'import datetime as dt\n'), ((8515, 8539), 'datetime.datetime', 'dt.datetime', (['(2016)', '(8)', '(10)'], {}), '(2016, 8, 10)\n', (8526, 8539), True, 'import datetime as dt\n'), ((8562, 8587), 'datetime.datetime', 'dt.datetime', (['(2016)', '(11)', '(25)'], {}), '(2016, 11, 25)\n', (8573, 8587), True, 'import datetime as dt\n'), ((13117, 13138), 'numpy.sum', 'np.sum', (['data.Paid_amt'], {}), '(data.Paid_amt)\n', (13123, 13138), True, 'import numpy as np\n'), ((17923, 17959), 'numpy.percentile', 'np.percentile', (['thisspec.frac_exp', '(90)'], {}), '(thisspec.frac_exp, 90)\n', (17936, 17959), True, 'import numpy as np\n'), ((20591, 20634), 'numpy.percentile', 'np.percentile', (['results.Paid_amt_x', '[25, 75]'], {}), '(results.Paid_amt_x, [25, 75])\n', (20604, 20634), True, 'import numpy as np\n'), ((20911, 20950), 'numpy.median', 'np.median', (['(outliers.Paid_amt_x - limval)'], {}), '(outliers.Paid_amt_x - limval)\n', (20920, 20950), True, 'import numpy as np\n'), ((4340, 4363), 'numpy.abs', 'np.abs', (['(limval - median)'], {}), '(limval - median)\n', (4346, 4363), True, 'import numpy as np\n'), ((7037, 7057), 'numpy.std', 'np.std', (['coords[:, 2]'], {}), '(coords[:, 2])\n', (7043, 7057), True, 'import numpy as np\n'), ((7374, 7388), 'numpy.min', 'np.min', (['distsq'], {}), '(distsq)\n', (7380, 7388), True, 'import numpy as np\n'), ((20713, 20750), 'numpy.percentile', 'np.percentile', (['results.Paid_amt_x', '(90)'], {}), '(results.Paid_amt_x, 90)\n', (20726, 20750), True, 'import numpy as np\n'), ((6987, 7007), 'numpy.std', 'np.std', (['coords[:, 0]'], {}), '(coords[:, 0])\n', (6993, 7007), True, 'import numpy as np\n'), ((7012, 7032), 'numpy.std', 'np.std', (['coords[:, 1]'], {}), '(coords[:, 1])\n', (7018, 7032), True, 'import numpy as np\n'), ((7302, 7315), 'numpy.array', 'np.array', (['pca'], {}), '(pca)\n', (7310, 7315), True, 'import numpy as np\n'), ((7318, 7345), 'numpy.array', 'np.array', (['center[iclus, :3]'], {}), '(center[iclus, :3])\n', (7326, 7345), True, 'import numpy as np\n'), ((7402, 7419), 'numpy.argmin', 'np.argmin', (['distsq'], {}), '(distsq)\n', (7411, 7419), True, 'import numpy as np\n')]
import numpy as np import base ##TODOs: implement ver.1 straightness function, bootstraping def straightness_moment_time(trial_trajectory, before_time=3): def _straight_line(start, end, length): _x = np.linspace(start[0], end[0], length) _y = np.linspace(start[1], end[1], length) return np.vstack([_x, _y]).T def _straight_length(start, end): return np.sqrt(np.sum((start - end)**2)) def travel_distance(traj): return np.cumsum(np.sqrt(np.sum((traj[1:] - traj[:-1])**2, axis=1)))[-1] time = trial_trajectory[:, 0] time_after = np.cumsum(np.flip(time[1:] - time[:-1])) if time_after[-1] > before_time: end_ind = np.where(time_after >= before_time)[0][0] trial_trajectory = np.flip(trial_trajectory[:, 1:3, ])[:end_ind] else: print('Time window exceeds the length of trajectory for this trial') return None straight_length = _straight_length(trial_trajectory[0], trial_trajectory[-1]) trajectory_displacement = travel_distance(trial_trajectory) straightness = straight_length / trajectory_displacement return straightness, np.array([trial_trajectory[0], trial_trajectory[-1]]), trial_trajectory def straightness_over_time(trial_trajectory, before_time=2): straightness = [] def _straight_line(start, end, length): _x = np.linspace(start[0], end[0], length) _y = np.linspace(start[1], end[1], length) return np.vstack([_x, _y]).T def _straight_length(start, end): return np.sqrt(np.sum((start - end)**2)) def travel_distance(traj): return np.cumsum(np.sqrt(np.sum((traj[1:] - traj[:-1])**2, axis=1)))[-1] time = trial_trajectory[:, 0] time_after = np.cumsum(np.flip(time[1:] - time[:-1])) if time_after[-1] > before_time: end_ind = np.where(time_after > before_time)[0][0] trial_trajectory = np.flip(trial_trajectory[:, 1:3, ], axis=0)[:end_ind] else: print('Time window exceeds the length of trajectory for this trial') return None for i in range(len(trial_trajectory) - 2): straight_length = _straight_length(trial_trajectory[i + 1], trial_trajectory[0]) trajectory_displacement = travel_distance(trial_trajectory[:i + 2]) straightness.append(straight_length / trajectory_displacement) return straightness, (trial_trajectory[0], trial_trajectory[-1]), trial_trajectory def bootstrap(trajectory, time_window=2, num_sampling=10, straightness_type='sliding'): ##trajectory = [time,x,y,z] ## sample sham trajectory from entire session randomly sham_straightness_list = [] shuffle_count = 1 while shuffle_count < num_sampling: random_index = np.random.randint(0, len(trajectory)) time = trajectory[random_index:, 0] time_cum = np.cumsum(time[1:] - time[:-1]) if time_cum[-1] > time_window: end_index = np.where(time_cum > time_window)[0][0] shuffle_count += 1 else: continue sampled_trajectory = trajectory[random_index:random_index + end_index + 100] if straightness_type == 'sliding': sham_straightness = straightness_over_time( sampled_trajectory, before_time=time_window)[0] elif straightness_type == 'fixed': sham_straightness = straightness_moment_time( sampled_trajectory, before_time=time_window)[0] sham_straightness_list.append(sham_straightness) return sham_straightness_list
[ "numpy.flip", "numpy.sum", "numpy.cumsum", "numpy.where", "numpy.array", "numpy.linspace", "numpy.vstack" ]
[((217, 254), 'numpy.linspace', 'np.linspace', (['start[0]', 'end[0]', 'length'], {}), '(start[0], end[0], length)\n', (228, 254), True, 'import numpy as np\n'), ((268, 305), 'numpy.linspace', 'np.linspace', (['start[1]', 'end[1]', 'length'], {}), '(start[1], end[1], length)\n', (279, 305), True, 'import numpy as np\n'), ((648, 677), 'numpy.flip', 'np.flip', (['(time[1:] - time[:-1])'], {}), '(time[1:] - time[:-1])\n', (655, 677), True, 'import numpy as np\n'), ((1229, 1282), 'numpy.array', 'np.array', (['[trial_trajectory[0], trial_trajectory[-1]]'], {}), '([trial_trajectory[0], trial_trajectory[-1]])\n', (1237, 1282), True, 'import numpy as np\n'), ((1481, 1518), 'numpy.linspace', 'np.linspace', (['start[0]', 'end[0]', 'length'], {}), '(start[0], end[0], length)\n', (1492, 1518), True, 'import numpy as np\n'), ((1532, 1569), 'numpy.linspace', 'np.linspace', (['start[1]', 'end[1]', 'length'], {}), '(start[1], end[1], length)\n', (1543, 1569), True, 'import numpy as np\n'), ((1912, 1941), 'numpy.flip', 'np.flip', (['(time[1:] - time[:-1])'], {}), '(time[1:] - time[:-1])\n', (1919, 1941), True, 'import numpy as np\n'), ((3145, 3176), 'numpy.cumsum', 'np.cumsum', (['(time[1:] - time[:-1])'], {}), '(time[1:] - time[:-1])\n', (3154, 3176), True, 'import numpy as np\n'), ((322, 341), 'numpy.vstack', 'np.vstack', (['[_x, _y]'], {}), '([_x, _y])\n', (331, 341), True, 'import numpy as np\n'), ((407, 433), 'numpy.sum', 'np.sum', (['((start - end) ** 2)'], {}), '((start - end) ** 2)\n', (413, 433), True, 'import numpy as np\n'), ((803, 836), 'numpy.flip', 'np.flip', (['trial_trajectory[:, 1:3]'], {}), '(trial_trajectory[:, 1:3])\n', (810, 836), True, 'import numpy as np\n'), ((1586, 1605), 'numpy.vstack', 'np.vstack', (['[_x, _y]'], {}), '([_x, _y])\n', (1595, 1605), True, 'import numpy as np\n'), ((1671, 1697), 'numpy.sum', 'np.sum', (['((start - end) ** 2)'], {}), '((start - end) ** 2)\n', (1677, 1697), True, 'import numpy as np\n'), ((2067, 2108), 'numpy.flip', 'np.flip', (['trial_trajectory[:, 1:3]'], {'axis': '(0)'}), '(trial_trajectory[:, 1:3], axis=0)\n', (2074, 2108), True, 'import numpy as np\n'), ((734, 769), 'numpy.where', 'np.where', (['(time_after >= before_time)'], {}), '(time_after >= before_time)\n', (742, 769), True, 'import numpy as np\n'), ((1999, 2033), 'numpy.where', 'np.where', (['(time_after > before_time)'], {}), '(time_after > before_time)\n', (2007, 2033), True, 'import numpy as np\n'), ((498, 541), 'numpy.sum', 'np.sum', (['((traj[1:] - traj[:-1]) ** 2)'], {'axis': '(1)'}), '((traj[1:] - traj[:-1]) ** 2, axis=1)\n', (504, 541), True, 'import numpy as np\n'), ((1762, 1805), 'numpy.sum', 'np.sum', (['((traj[1:] - traj[:-1]) ** 2)'], {'axis': '(1)'}), '((traj[1:] - traj[:-1]) ** 2, axis=1)\n', (1768, 1805), True, 'import numpy as np\n'), ((3240, 3272), 'numpy.where', 'np.where', (['(time_cum > time_window)'], {}), '(time_cum > time_window)\n', (3248, 3272), True, 'import numpy as np\n')]
""" reference: https://github.com/pierluigiferrari/ssd_keras/blob/master/keras_layers/keras_layer_AnchorBoxes.py """ import tensorflow as tf import numpy as np from .bounding_box_utils import convert_coordinates from keras import backend as K def AnchorBoxes(x, img_height, img_width, this_scale, next_scale, aspect_ratios=[0.5, 1.0, 2.0], two_boxes_for_ar1=True, this_steps=None, this_offsets=None, clip_boxes=False, variances=[0.1, 0.1, 0.2, 0.2], coords='centroids', normalize_coords=False, batch_size=1): ''' A TensorFlow layer to create an output tensor containing anchor box coordinates and variances based on the input tensor and the passed arguments. A set of 2D anchor boxes of different aspect ratios is created for each spatial unit of the input tensor. The number of anchor boxes created per unit depends on the arguments `aspect_ratios` and `two_boxes_for_ar1`, in the default case it is 4. The boxes are parameterized by the coordinate tuple `(xmin, xmax, ymin, ymax)`. The logic implemented by this layer is identical to the logic in the module `ssd_box_encode_decode_utils.py`. The purpose of having this layer in the network is to make the model self-sufficient at inference time. Since the model is predicting offsets to the anchor boxes (rather than predicting absolute box coordinates directly), one needs to know the anchor box coordinates in order to construct the final prediction boxes from the predicted offsets. If the model's output tensor did not contain the anchor box coordinates, the necessary information to convert the predicted offsets back to absolute coordinates would be missing in the model output. The reason why it is necessary to predict offsets to the anchor boxes rather than to predict absolute box coordinates directly is explained in `README.md`. Input shape: 4D tensor of shape `(batch, channels, height, width)` if `dim_ordering = 'th'` or `(batch, height, width, channels)` if `dim_ordering = 'tf'`. Output shape: 5D tensor of shape `(batch, height, width, n_boxes, 8)`. The last axis contains the four anchor box coordinates and the four variance values for each box. ''' if (this_scale < 0) or (next_scale < 0) or (this_scale > 1): raise ValueError( "`this_scale` must be in [0, 1] and `next_scale` must be >0, but `this_scale` == {}, `next_scale` == {}".format( this_scale, next_scale)) if len(variances) != 4: raise ValueError("4 variance values must be pased, but {} values were received.".format(len(variances))) variances = np.array(variances) if np.any(variances <= 0): raise ValueError("All variances must be >0, but the variances given are {}".format(variances)) # Compute the number of boxes per cell if (1 in aspect_ratios) and two_boxes_for_ar1: n_boxes = len(aspect_ratios) + 1 else: n_boxes = len(aspect_ratios) # Compute box width and height for each aspect ratio # The shorter side of the image will be used to compute `w` and `h` using `scale` and `aspect_ratios`. size = min(img_height, img_width) wh_list = [] for ar in aspect_ratios: if ar == 1: # Compute the regular anchor box for aspect ratio 1. box_height = box_width = this_scale * size wh_list.append((box_width, box_height)) if two_boxes_for_ar1: # Compute one slightly larger version using the geometric mean of this scale value and the next. box_height = box_width = np.sqrt(this_scale * next_scale) * size wh_list.append((box_width, box_height)) else: box_height = this_scale * size / np.sqrt(ar) box_width = this_scale * size * np.sqrt(ar) wh_list.append((box_width, box_height)) wh_list = np.array(wh_list) # We need the shape of the input tensor feature_map_height = x.get_shape().as_list()[1] feature_map_width = x.get_shape().as_list()[2] # Compute the grid of box center points. They are identical for all aspect ratios. # Compute the step sizes, i.e. how far apart the anchor box center points will be vertically and horizontally. if (this_steps is None): step_height = img_height / feature_map_height step_width = img_width / feature_map_width else: if isinstance(this_steps, (list, tuple)) and (len(this_steps) == 2): step_height = this_steps[0] step_width = this_steps[1] elif isinstance(this_steps, (int, float)): step_height = this_steps step_width = this_steps # Compute the offsets, i.e. at what pixel values the first anchor box center point will be from the top and from the left of the image. if (this_offsets is None): offset_height = 0.5 offset_width = 0.5 else: if isinstance(this_offsets, (list, tuple)) and (len(this_offsets) == 2): offset_height = this_offsets[0] offset_width = this_offsets[1] elif isinstance(this_offsets, (int, float)): offset_height = this_offsets offset_width = this_offsets # Now that we have the offsets and step sizes, compute the grid of anchor box center points. cy = np.linspace(offset_height * step_height, (offset_height + feature_map_height - 1) * step_height, feature_map_height) cx = np.linspace(offset_width * step_width, (offset_width + feature_map_width - 1) * step_width, feature_map_width) cx_grid, cy_grid = np.meshgrid(cx, cy) cx_grid = np.expand_dims(cx_grid, -1) # This is necessary for np.tile() to do what we want further down cy_grid = np.expand_dims(cy_grid, -1) # This is necessary for np.tile() to do what we want further down # Create a 4D tensor template of shape `(feature_map_height, feature_map_width, n_boxes, 4)` # where the last dimension will contain `(cx, cy, w, h)` boxes_tensor = np.zeros((feature_map_height, feature_map_width, n_boxes, 4)) boxes_tensor[:, :, :, 0] = np.tile(cx_grid, (1, 1, n_boxes)) # Set cx boxes_tensor[:, :, :, 1] = np.tile(cy_grid, (1, 1, n_boxes)) # Set cy boxes_tensor[:, :, :, 2] = wh_list[:, 0] # Set w boxes_tensor[:, :, :, 3] = wh_list[:, 1] # Set h # Convert `(cx, cy, w, h)` to `(xmin, xmax, ymin, ymax)` boxes_tensor = convert_coordinates(boxes_tensor, start_index=0, conversion='centroids2corners') # If `clip_boxes` is enabled, clip the coordinates to lie within the image boundaries if clip_boxes: x_coords = boxes_tensor[:, :, :, [0, 2]] x_coords[x_coords >= img_width] = img_width - 1 x_coords[x_coords < 0] = 0 boxes_tensor[:, :, :, [0, 2]] = x_coords y_coords = boxes_tensor[:, :, :, [1, 3]] y_coords[y_coords >= img_height] = img_height - 1 y_coords[y_coords < 0] = 0 boxes_tensor[:, :, :, [1, 3]] = y_coords # If `normalize_coords` is enabled, normalize the coordinates to be within [0,1] if normalize_coords: boxes_tensor[:, :, :, [0, 2]] /= img_width boxes_tensor[:, :, :, [1, 3]] /= img_height if coords == 'centroids': # Convert `(xmin, ymin, xmax, ymax)` back to `(cx, cy, w, h)`. boxes_tensor = convert_coordinates(boxes_tensor, start_index=0, conversion='corners2centroids', border_pixels='half') elif coords == 'minmax': # Convert `(xmin, ymin, xmax, ymax)` to `(xmin, xmax, ymin, ymax). boxes_tensor = convert_coordinates(boxes_tensor, start_index=0, conversion='corners2minmax', border_pixels='half') # Create a tensor to contain the variances and append it to `boxes_tensor`. This tensor has the same shape # as `boxes_tensor` and simply contains the same 4 variance values for every position in the last axis. variances_tensor = np.zeros_like(boxes_tensor) # Has shape `(feature_map_height, feature_map_width, n_boxes, 4)` variances_tensor += variances # Long live broadcasting # Now `boxes_tensor` becomes a tensor of shape `(feature_map_height, feature_map_width, n_boxes, 8)` boxes_tensor = np.concatenate((boxes_tensor, variances_tensor), axis=-1) # Now prepend one dimension to `boxes_tensor` to account for the batch size and tile it along # The result will be a 5D tensor of shape `(batch_size, feature_map_height, feature_map_width, n_boxes, 8)` boxes_tensor = np.expand_dims(boxes_tensor, axis=0) # revised boxes_tensor = tf.tile(tf.constant(boxes_tensor, dtype='float32'), [batch_size, 1, 1, 1, 1]) return boxes_tensor
[ "numpy.meshgrid", "numpy.zeros_like", "numpy.zeros", "numpy.expand_dims", "tensorflow.constant", "numpy.any", "numpy.array", "numpy.tile", "numpy.linspace", "numpy.concatenate", "numpy.sqrt" ]
[((3001, 3020), 'numpy.array', 'np.array', (['variances'], {}), '(variances)\n', (3009, 3020), True, 'import numpy as np\n'), ((3029, 3051), 'numpy.any', 'np.any', (['(variances <= 0)'], {}), '(variances <= 0)\n', (3035, 3051), True, 'import numpy as np\n'), ((4285, 4302), 'numpy.array', 'np.array', (['wh_list'], {}), '(wh_list)\n', (4293, 4302), True, 'import numpy as np\n'), ((5752, 5872), 'numpy.linspace', 'np.linspace', (['(offset_height * step_height)', '((offset_height + feature_map_height - 1) * step_height)', 'feature_map_height'], {}), '(offset_height * step_height, (offset_height +\n feature_map_height - 1) * step_height, feature_map_height)\n', (5763, 5872), True, 'import numpy as np\n'), ((5879, 5994), 'numpy.linspace', 'np.linspace', (['(offset_width * step_width)', '((offset_width + feature_map_width - 1) * step_width)', 'feature_map_width'], {}), '(offset_width * step_width, (offset_width + feature_map_width - \n 1) * step_width, feature_map_width)\n', (5890, 5994), True, 'import numpy as np\n'), ((6014, 6033), 'numpy.meshgrid', 'np.meshgrid', (['cx', 'cy'], {}), '(cx, cy)\n', (6025, 6033), True, 'import numpy as np\n'), ((6049, 6076), 'numpy.expand_dims', 'np.expand_dims', (['cx_grid', '(-1)'], {}), '(cx_grid, -1)\n', (6063, 6076), True, 'import numpy as np\n'), ((6158, 6185), 'numpy.expand_dims', 'np.expand_dims', (['cy_grid', '(-1)'], {}), '(cy_grid, -1)\n', (6172, 6185), True, 'import numpy as np\n'), ((6434, 6495), 'numpy.zeros', 'np.zeros', (['(feature_map_height, feature_map_width, n_boxes, 4)'], {}), '((feature_map_height, feature_map_width, n_boxes, 4))\n', (6442, 6495), True, 'import numpy as np\n'), ((6530, 6563), 'numpy.tile', 'np.tile', (['cx_grid', '(1, 1, n_boxes)'], {}), '(cx_grid, (1, 1, n_boxes))\n', (6537, 6563), True, 'import numpy as np\n'), ((6606, 6639), 'numpy.tile', 'np.tile', (['cy_grid', '(1, 1, n_boxes)'], {}), '(cy_grid, (1, 1, n_boxes))\n', (6613, 6639), True, 'import numpy as np\n'), ((8442, 8469), 'numpy.zeros_like', 'np.zeros_like', (['boxes_tensor'], {}), '(boxes_tensor)\n', (8455, 8469), True, 'import numpy as np\n'), ((8724, 8781), 'numpy.concatenate', 'np.concatenate', (['(boxes_tensor, variances_tensor)'], {'axis': '(-1)'}), '((boxes_tensor, variances_tensor), axis=-1)\n', (8738, 8781), True, 'import numpy as np\n'), ((9016, 9052), 'numpy.expand_dims', 'np.expand_dims', (['boxes_tensor'], {'axis': '(0)'}), '(boxes_tensor, axis=0)\n', (9030, 9052), True, 'import numpy as np\n'), ((9096, 9138), 'tensorflow.constant', 'tf.constant', (['boxes_tensor'], {'dtype': '"""float32"""'}), "(boxes_tensor, dtype='float32')\n", (9107, 9138), True, 'import tensorflow as tf\n'), ((4148, 4159), 'numpy.sqrt', 'np.sqrt', (['ar'], {}), '(ar)\n', (4155, 4159), True, 'import numpy as np\n'), ((4205, 4216), 'numpy.sqrt', 'np.sqrt', (['ar'], {}), '(ar)\n', (4212, 4216), True, 'import numpy as np\n'), ((3990, 4022), 'numpy.sqrt', 'np.sqrt', (['(this_scale * next_scale)'], {}), '(this_scale * next_scale)\n', (3997, 4022), True, 'import numpy as np\n')]
import math import operator import cv2 import numpy as np import dito.core import dito.visual ## ## basic processing ## def gaussian_blur(image, sigma): if sigma <= 0.0: return image return cv2.GaussianBlur(src=image, ksize=None, sigmaX=sigma) def median_blur(image, kernel_size): return cv2.medianBlur(src=image, ksize=kernel_size) ## ## thresholding ## def otsu(image): if dito.core.is_color(image=image): raise ValueError("Expected gray image but got color image for Otsu thresholding") (theta, image2) = cv2.threshold(src=image, thresh=-1, maxval=255, type=cv2.THRESH_BINARY | cv2.THRESH_OTSU) return (theta, image2) def otsu_theta(image): (theta, image2) = otsu(image=image) return theta def otsu_image(image): (theta, image2) = otsu(image=image) return image2 ## ## morphological operations ## def morpho_op_kernel(shape, size): ksize = dito.utils.get_validated_tuple(x=size, type_=int, count=2) kernel = cv2.getStructuringElement(shape=shape, ksize=ksize, anchor=(-1, -1)) return kernel def morpho_op(image, operation, shape=cv2.MORPH_ELLIPSE, size=3, anchor=(-1, -1), iterations=1): kernel = morpho_op_kernel(shape=shape, size=size) return cv2.morphologyEx(src=image, op=operation, kernel=kernel, anchor=anchor, iterations=iterations) def dilate(image, **kwargs): return morpho_op(image=image, operation=cv2.MORPH_DILATE, **kwargs) def erode(image, **kwargs): return morpho_op(image=image, operation=cv2.MORPH_ERODE, **kwargs) def morpho_open(image, **kwargs): return morpho_op(image=image, operation=cv2.MORPH_OPEN, **kwargs) def morpho_close(image, **kwargs): return morpho_op(image=image, operation=cv2.MORPH_CLOSE, **kwargs) def blackhat(image, **kwargs): return morpho_op(image=image, operation=cv2.MORPH_BLACKHAT, **kwargs) def tophat(image, **kwargs): return morpho_op(image=image, operation=cv2.MORPH_TOPHAT, **kwargs) ## ## filters ## def dog(image, sigma1, sigma2, return_raw=False, colormap=None): blur1 = gaussian_blur(image=image, sigma=sigma1).astype(np.float32) blur2 = gaussian_blur(image=image, sigma=sigma2).astype(np.float32) diff = blur1 - blur2 if return_raw: return diff else: diff_11 = diff / dito.core.dtype_range(dtype=image.dtype)[1] diff_01 = (diff_11 + 1.0) * 0.5 result = dito.convert(image=diff_01, dtype=image.dtype) if colormap is not None: result = dito.visual.colorize(image=result, colormap=colormap) return result def dog_interactive(image, colormap=None): window_name = "dito.dog_interactive" sliders = [dito.highgui.FloatSlider(window_name=window_name, name="sigma{}".format(n_slider + 1), min_value=0.0, max_value=15.0, value_count=1001) for n_slider in range(2)] sliders[0].set_value(0.5) sliders[1].set_value(0.8) image_show = None while True: if (image_show is None) or any(slider.changed for slider in sliders): sigmas = [sliders[n_slider].get_value() for n_slider in range(2)] images_blur = [gaussian_blur(image=image, sigma=sigmas[n_slider]) for n_slider in range(2)] images_blur = [dito.visual.text(image=image_blur, message="sigma{} = {:.2f}".format(n_slider + 1, sigmas[n_slider])) for (n_slider, image_blur) in enumerate(images_blur)] image_dog = dog(image, sigma1=sigmas[0], sigma2=sigmas[1], return_raw=False, colormap=colormap) image_show = dito.stack([[image, image_dog], images_blur]) key = dito.show(image=image_show, window_name=window_name, wait=10) if key in dito.qkeys(): return ## ## contours ## class Contour(): def __init__(self, points): self.points = points def __len__(self): """ Returns the number of points. """ return len(self.points) def __eq__(self, other): if not isinstance(other, Contour): raise TypeError("Argument 'other' must be a contour") if len(self) != len(other): return False return np.array_equal(self.points, other.points) def copy(self): return Contour(points=self.points.copy()) def get_center(self): return np.mean(self.points, axis=0) def get_center_x(self): return np.mean(self.points[:, 0]) def get_center_y(self): return np.mean(self.points[:, 1]) def get_min_x(self): return np.min(self.points[:, 0]) def get_max_x(self): return np.max(self.points[:, 0]) def get_width(self): return self.get_max_x() - self.get_min_x() def get_min_y(self): return np.min(self.points[:, 1]) def get_max_y(self): return np.max(self.points[:, 1]) def get_height(self): return self.get_max_y() - self.get_min_y() def get_area(self, mode="draw"): if mode == "draw": image = self.draw_standalone(color=(1,), thickness=1, filled=True, antialias=False, border=2) return np.sum(image) elif mode == "calc": return cv2.contourArea(contour=self.points) else: raise ValueError("Invalid value for argument 'mode': '{}'".format(mode)) def get_perimeter(self): return cv2.arcLength(curve=self.points, closed=True) def get_circularity(self): r_area = np.sqrt(self.get_area() / np.pi) r_perimeter = self.get_perimeter() / (2.0 * np.pi) return r_area / r_perimeter def get_ellipse(self): return cv2.fitEllipse(points=self.points) def get_eccentricity(self): ellipse = self.get_ellipse() (width, height) = ellipse[1] semi_major_axis = max(width, height) * 0.5 semi_minor_axis = min(width, height) * 0.5 eccentricity = math.sqrt(1.0 - (semi_minor_axis / semi_major_axis)**2) return eccentricity def get_moments(self): return cv2.moments(array=self.points, binaryImage=False) def get_hu_moments(self, log=True): hu_moments = cv2.HuMoments(m=self.get_moments()) if log: return np.sign(hu_moments) * np.log10(np.abs(hu_moments)) else: return hu_moments def shift(self, offset_x=None, offset_y=None): if offset_x is not None: self.points[:, 0] += offset_x if offset_y is not None: self.points[:, 1] += offset_y def draw(self, image, color, thickness=1, filled=True, antialias=False, offset=None): cv2.drawContours(image=image, contours=[np.round(self.points).astype(np.int)], contourIdx=0, color=color, thickness=cv2.FILLED if filled else thickness, lineType=cv2.LINE_AA if antialias else cv2.LINE_8, offset=offset) def draw_standalone(self, color, thickness=1, filled=True, antialias=False, border=0): image = np.zeros(shape=(2 * border + self.get_height(), 2 * border + self.get_width()), dtype=np.uint8) self.draw(image=image, color=color, thickness=thickness, filled=filled, antialias=antialias, offset=(border - self.get_min_x(), border - self.get_min_y())) return image class ContourList(): def __init__(self, contours): self.contours = contours def __len__(self): """ Returns the number of found contours. """ return len(self.contours) def __eq__(self, other): if not isinstance(other, ContourList): raise TypeError("Argument 'other' must be a contour list") if len(self) != len(other): return False for (contour_self, contour_other) in zip(self.contours, other.contours): if contour_self != contour_other: return False return True def __getitem__(self, key): return self.contours[key] def copy(self): contours_copy = [contour.copy() for contour in self.contours] return ContourList(contours=contours_copy) def filter(self, func, min_value=None, max_value=None): if (min_value is None) and (max_value is None): # nothing to do return # filter contours_filtered = [] for contour in self.contours: value = func(contour) if (min_value is not None) and (value < min_value): continue if (max_value is not None) and (value > max_value): continue contours_filtered.append(contour) self.contours = contours_filtered def filter_center_x(self, min_value=None, max_value=None): self.filter(func=operator.methodcaller("get_center_x"), min_value=min_value, max_value=max_value) def filter_center_y(self, min_value=None, max_value=None): self.filter(func=operator.methodcaller("get_center_y"), min_value=min_value, max_value=max_value) def filter_area(self, min_value=None, max_value=None, mode="draw"): self.filter(func=operator.methodcaller("get_area", mode=mode), min_value=min_value, max_value=max_value) def filter_perimeter(self, min_value=None, max_value=None): self.filter(func=operator.methodcaller("get_perimeter"), min_value=min_value, max_value=max_value) def filter_circularity(self, min_value=None, max_value=None): self.filter(func=operator.methodcaller("get_circularity"), min_value=min_value, max_value=max_value) def find_largest(self, return_index=True): """ Returns the index of the largest (area-wise) contour. """ max_area = None argmax_area = None for (n_contour, contour) in enumerate(self.contours): area = contour.get_area() if (max_area is None) or (area > max_area): max_area = area argmax_area = n_contour if argmax_area is None: return None else: if return_index: return argmax_area else: return self.contours[argmax_area] def draw_all(self, image, colors=None, **kwargs): if colors is None: colors = tuple(dito.random_color() for _ in range(len(self))) for (contour, color) in zip(self.contours, colors): contour.draw(image=image, color=color, **kwargs) class ContourFinder(ContourList): def __init__(self, image): self.image = image.copy() if self.image.dtype == np.bool: self.image = dito.core.convert(image=self.image, dtype=np.uint8) contours = self.find_contours(image=self.image) super().__init__(contours=contours) @staticmethod def find_contours(image): """ Called internally to find the contours in the given `image`. """ # find raw contours result = cv2.findContours(image=image, mode=cv2.RETR_LIST, method=cv2.CHAIN_APPROX_NONE) # compatible with OpenCV 3.x and 4.x, see https://stackoverflow.com/a/53909713/1913780 contours_raw = result[-2] # return tuple of instances of class `Contour` return [Contour(points=contour_raw[:, 0, :]) for contour_raw in contours_raw] def contours(image): """ Convenience wrapper for `ContourFinder`. """ contour_finder = ContourFinder(image=image) return contour_finder.contours class VoronoiPartition(ContourList): def __init__(self, image_size, points): contours = self.get_facets(image_size=image_size, points=points) super().__init__(contours=contours) @staticmethod def get_facets(image_size, points): subdiv = cv2.Subdiv2D((0, 0, image_size[0], image_size[1])) for point in points: subdiv.insert(pt=point) (voronoi_facets, voronoi_centers) = subdiv.getVoronoiFacetList(idx=[]) return [Contour(voronoi_facet) for voronoi_facet in voronoi_facets] def voronoi(image_size, points): voronoi_partition = VoronoiPartition(image_size=image_size, points=points) return voronoi_partition.contours
[ "cv2.GaussianBlur", "numpy.sum", "numpy.abs", "cv2.medianBlur", "cv2.arcLength", "numpy.mean", "numpy.round", "cv2.contourArea", "operator.methodcaller", "numpy.max", "cv2.fitEllipse", "cv2.Subdiv2D", "math.sqrt", "cv2.morphologyEx", "numpy.min", "cv2.getStructuringElement", "cv2.thr...
[((212, 265), 'cv2.GaussianBlur', 'cv2.GaussianBlur', ([], {'src': 'image', 'ksize': 'None', 'sigmaX': 'sigma'}), '(src=image, ksize=None, sigmaX=sigma)\n', (228, 265), False, 'import cv2\n'), ((316, 360), 'cv2.medianBlur', 'cv2.medianBlur', ([], {'src': 'image', 'ksize': 'kernel_size'}), '(src=image, ksize=kernel_size)\n', (330, 360), False, 'import cv2\n'), ((556, 649), 'cv2.threshold', 'cv2.threshold', ([], {'src': 'image', 'thresh': '(-1)', 'maxval': '(255)', 'type': '(cv2.THRESH_BINARY | cv2.THRESH_OTSU)'}), '(src=image, thresh=-1, maxval=255, type=cv2.THRESH_BINARY |\n cv2.THRESH_OTSU)\n', (569, 649), False, 'import cv2\n'), ((995, 1063), 'cv2.getStructuringElement', 'cv2.getStructuringElement', ([], {'shape': 'shape', 'ksize': 'ksize', 'anchor': '(-1, -1)'}), '(shape=shape, ksize=ksize, anchor=(-1, -1))\n', (1020, 1063), False, 'import cv2\n'), ((1246, 1344), 'cv2.morphologyEx', 'cv2.morphologyEx', ([], {'src': 'image', 'op': 'operation', 'kernel': 'kernel', 'anchor': 'anchor', 'iterations': 'iterations'}), '(src=image, op=operation, kernel=kernel, anchor=anchor,\n iterations=iterations)\n', (1262, 1344), False, 'import cv2\n'), ((4122, 4163), 'numpy.array_equal', 'np.array_equal', (['self.points', 'other.points'], {}), '(self.points, other.points)\n', (4136, 4163), True, 'import numpy as np\n'), ((4277, 4305), 'numpy.mean', 'np.mean', (['self.points'], {'axis': '(0)'}), '(self.points, axis=0)\n', (4284, 4305), True, 'import numpy as np\n'), ((4350, 4376), 'numpy.mean', 'np.mean', (['self.points[:, 0]'], {}), '(self.points[:, 0])\n', (4357, 4376), True, 'import numpy as np\n'), ((4421, 4447), 'numpy.mean', 'np.mean', (['self.points[:, 1]'], {}), '(self.points[:, 1])\n', (4428, 4447), True, 'import numpy as np\n'), ((4489, 4514), 'numpy.min', 'np.min', (['self.points[:, 0]'], {}), '(self.points[:, 0])\n', (4495, 4514), True, 'import numpy as np\n'), ((4556, 4581), 'numpy.max', 'np.max', (['self.points[:, 0]'], {}), '(self.points[:, 0])\n', (4562, 4581), True, 'import numpy as np\n'), ((4700, 4725), 'numpy.min', 'np.min', (['self.points[:, 1]'], {}), '(self.points[:, 1])\n', (4706, 4725), True, 'import numpy as np\n'), ((4767, 4792), 'numpy.max', 'np.max', (['self.points[:, 1]'], {}), '(self.points[:, 1])\n', (4773, 4792), True, 'import numpy as np\n'), ((5306, 5351), 'cv2.arcLength', 'cv2.arcLength', ([], {'curve': 'self.points', 'closed': '(True)'}), '(curve=self.points, closed=True)\n', (5319, 5351), False, 'import cv2\n'), ((5572, 5606), 'cv2.fitEllipse', 'cv2.fitEllipse', ([], {'points': 'self.points'}), '(points=self.points)\n', (5586, 5606), False, 'import cv2\n'), ((5839, 5896), 'math.sqrt', 'math.sqrt', (['(1.0 - (semi_minor_axis / semi_major_axis) ** 2)'], {}), '(1.0 - (semi_minor_axis / semi_major_axis) ** 2)\n', (5848, 5896), False, 'import math\n'), ((5966, 6015), 'cv2.moments', 'cv2.moments', ([], {'array': 'self.points', 'binaryImage': '(False)'}), '(array=self.points, binaryImage=False)\n', (5977, 6015), False, 'import cv2\n'), ((10793, 10872), 'cv2.findContours', 'cv2.findContours', ([], {'image': 'image', 'mode': 'cv2.RETR_LIST', 'method': 'cv2.CHAIN_APPROX_NONE'}), '(image=image, mode=cv2.RETR_LIST, method=cv2.CHAIN_APPROX_NONE)\n', (10809, 10872), False, 'import cv2\n'), ((11588, 11638), 'cv2.Subdiv2D', 'cv2.Subdiv2D', (['(0, 0, image_size[0], image_size[1])'], {}), '((0, 0, image_size[0], image_size[1]))\n', (11600, 11638), False, 'import cv2\n'), ((5061, 5074), 'numpy.sum', 'np.sum', (['image'], {}), '(image)\n', (5067, 5074), True, 'import numpy as np\n'), ((5124, 5160), 'cv2.contourArea', 'cv2.contourArea', ([], {'contour': 'self.points'}), '(contour=self.points)\n', (5139, 5160), False, 'import cv2\n'), ((6149, 6168), 'numpy.sign', 'np.sign', (['hu_moments'], {}), '(hu_moments)\n', (6156, 6168), True, 'import numpy as np\n'), ((8608, 8645), 'operator.methodcaller', 'operator.methodcaller', (['"""get_center_x"""'], {}), "('get_center_x')\n", (8629, 8645), False, 'import operator\n'), ((8778, 8815), 'operator.methodcaller', 'operator.methodcaller', (['"""get_center_y"""'], {}), "('get_center_y')\n", (8799, 8815), False, 'import operator\n'), ((8957, 9001), 'operator.methodcaller', 'operator.methodcaller', (['"""get_area"""'], {'mode': 'mode'}), "('get_area', mode=mode)\n", (8978, 9001), False, 'import operator\n'), ((9135, 9173), 'operator.methodcaller', 'operator.methodcaller', (['"""get_perimeter"""'], {}), "('get_perimeter')\n", (9156, 9173), False, 'import operator\n'), ((9309, 9349), 'operator.methodcaller', 'operator.methodcaller', (['"""get_circularity"""'], {}), "('get_circularity')\n", (9330, 9349), False, 'import operator\n'), ((6180, 6198), 'numpy.abs', 'np.abs', (['hu_moments'], {}), '(hu_moments)\n', (6186, 6198), True, 'import numpy as np\n'), ((6585, 6606), 'numpy.round', 'np.round', (['self.points'], {}), '(self.points)\n', (6593, 6606), True, 'import numpy as np\n')]
# -*- coding: utf-8 -*- import sys import rospy import math import numpy as np import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D,art3d from sensor_msgs.msg import PointCloud2, LaserScan, NavSatFix from sensor_msgs import point_cloud2 from helper.utils import * from helper.ambiente import Pontos from classic import rrt_connect_3d as alg from nav_msgs.msg import Odometry from sensor_msgs.msg import Range from geometry_msgs.msg import PoseArray, Pose from tf.transformations import euler_from_quaternion from std_msgs.msg import String, Int32 from sensor_msgs.msg import BatteryState from datetime import datetime import statistics as stc from haversine import haversine from sys import exit import psutil from utilsUAV import * class globalPlanner: def __init__(self): self.memoriaDoPc = 16000 # MB self.processadorDoPc = 2800 # MHz ph = [[[0.0, 10.0], [0.0, 0.0]], [[0.0, 10.0], [10.0, 10.0]], [[6.5, 8.5], [2.0, 2.0]], [[2.0, 4.5], [8.5, 8.5]], [[2.0, 6.5], [4.0, 4.0]], [[3.5, 5.0], [5.2, 5.2]], [[5.0, 6.5], [6.4, 6.4]], [[8.0, 9.0], [8.0, 8.0]], [[6.5, 8.0], [5.2, 5.2]], [[2.0, 4.5], [2.0, 2.0]]] pv = [[[10.0, 10.0], [0.0, 10.0]], [[0.0, 0.0], [0.0, 10.0]], [[4.5, 4.5], [0.0, 2.0]], [[2.0, 2.0], [4.0, 8.5]], [[3.5, 3.5], [4.0, 5.2]], [[5.0, 5.0], [5.2, 6.4]], [[6.5, 6.5], [6.4, 8.7]], [[8.0, 8.0], [8.0, 10.0]], [[9.0, 9.0], [5.2, 8.0]], [[6.5, 6.5], [2.0, 5.2]], [[8.0, 8.0], [3.5, 5.2]]] self.xx, self.yy = [], [] for i in range(len(ph)): for j in range(int(ph[i][0][0]*10.0), int(ph[i][0][1]*10.0), 1): self.xx.append(j) self.yy.append(int(ph[i][1][0]*10.0)) for i in range(len(pv)): for j in range(int(pv[i][1][0]*10.0), int(pv[i][1][1]*10.0), 1): self.xx.append(int(pv[i][0][0]*10.0)) self.yy.append(j) # Tags self.land, self.takeoff, self.hover, self.sec, self.garraOn, self.esperarCamera, self.garraOff, self.calibrarTarget = 100, 200, 300, 400, 500, 600, 700, 800 # Flags self.addRota = 0 self.log = 0 self.pos = 0 self.goToHome = 0 self.letra = "" self.unic = {"SM": 0, "busy": 0, "print": 0, "hover": 0, "definirRota": 0, "sec": 0, "andar": 0, "bateria": 0, "bateriaGazebo": 0, "gpsrtk": 0} self.rotina = {"normal": 0, "visao": 0} self.velodyne = 1 self.trajetoriaCalculada = 0 self.avoidStatic = 0 # Mapa self.p = Pontos() self.distanciaObsPerto = 5 self.a, self.b, self.c, self.abc, self.a1, self.b1, self.c1, self.a1b1c1 = [0,self.p.limiar[0]], [0,self.p.limiar[1]], [0,20], [[0,0,0], [100,100,100]], [0,100], [0,100], [0,100], [[0,0,0],[100,100,100]] # a,b = com capa | a1,b1 = sem capa self.newA, self.newB, self.newC, self.newA1, self.newB1, self.newC1, self.newA2, self.newB2, self.newC2 = [], [], [], [], [], [], [], [], [] self.ABC, self.ABC1, self.ABC2 = [], [], [] self.countDym, self.checkDym = 0, 0 self.localX, self.localY, self.localXY = [], [], [] # Variable Values self.rand = 0 self.anguloGeral = 0.0 self.altura, self.distNodes = 2.2, 1 self.currentPosX, self.currentPosY, self.currentPosZ, self.currentPosYaw = 2, 2, 0, 0 self.alturaLaser = 0 self.bateria = {"inicial": 0, "final": 0, "uso": 0, "atual": 0} self.bateriaGazebo = {"inicial": 0, "final": 0, "uso": 0, "atual": 0} self.memoria = {"inicial": 0, "final": 0} self.cpu = {"inicial": 0, "final": 0} self.zero = {"rtkx": 0, "rtky": 0, "rtkz": 0} self.variaveisLog = {"tt": []} self.knownEnvironment = 0 self.controller = 1 # Use 1 to MPC and 0 to cmd_vel # Trajectory self.rotas = {} self.rotas["x"], self.rotas["y"], self.rotas["z"], self.rotas["yaw"] = np.array([]), np.array([]), np.array([]), np.array([]) # Values to be Changed by the User # self.rotas["x"] = [7.1, 10, 11, 12, 15, 17, 20, 20.1] # self.rotas["y"] = [7.1, 10, 11, 12, 12, 11, 15, 15.1] # # self.rotas["x"] = np.array([7.1]) # # self.rotas["y"] = np.array([7.1]) # self.rotas["z"] = np.array([self.altura] * len(self.rotas["x"])) # self.rotas["yaw"] = np.array([0] * len(self.rotas["x"])) # Generate Trajectory # _, t, rx, ry = alg.run(show=0, vmx=self.a, vmy=self.b, vmz=self.c, startx=self.currentPosX, starty=self.currentPosY, startz=self.currentPosZ, p1=self.p) # To Log # fileName = "logPathPlanner/comUAV/" + "RRT" + str(datetime.now().day) + str(datetime.now().month) + str(datetime.now().hour) + str(datetime.now().minute) + str(datetime.now().second) + ".txt" fileName = "logPathPlanner/comUAV/" + "Velodynee" + str(datetime.now().day) + str(datetime.now().month) + str(datetime.now().hour) + str(datetime.now().minute) + str(datetime.now().second) + ".txt" if self.log: print("NOME DO ARQUIVO: " + str(fileName)) self.f = open(fileName, "a") # self.f = open(fileName, "a") # self.variaveisLog["tt"].append(t) # Adjust Trajectory # self.rotas["x"], self.rotas["y"] = rotaToGazebo(rx, ry, self.a, self.b, self.distNodes) # self.rotas["z"] = [self.altura] * len(self.rotas["x"]) # self.rotas["yaw"] = [0] * len(self.rotas["x"]) # Times self.counts = {"total": 0, "parar": 0, "tempo": 0, "calibrandoTarget": 0} self.tempo = {"parar": 0, "takeoff": 6, "land": 6, "wait": 0, "hover": 6, "sec": 2} self.contador,self.contador0 = 0, 0 self.theLast = 0 self.contadorTotal = time() # Start self.counts["total"] = time() sleeping(t=1) # State Machine self.status = 2 self.busy, self.arrived, self.idle = 1, 2, 3 self.numeroImagem = 0 # Subscribers ############# Main _ = rospy.Subscriber("/uav1/odometry/odom_local", Odometry, self.callbackMain) ############# Localization _ = rospy.Subscriber("/uav1/odometry/odom_main", Odometry, self.callbackPosicao) # # _ = rospy.Subscriber("/uav1/garmin/range", Range, self.callbackLaser) # _ = rospy.Subscriber("/tcpfix", NavSatFix, self.callbackGPSRTK) ############# Battery # _ = rospy.Subscriber("/uav1/mavros/battery", BatteryState, self.callbackBattery) # # # _ = rospy.Subscriber("/battery/status", BatteryState, self.callbackBatteryGazebo) # 18 _ = rospy.Subscriber("/battery/percent", Int32, self.callbackBatteryGazebo) # 20 ############# Avoid Obstacle # _ = rospy.Subscriber("/uav1/odometry/odom_main_innovation", Odometry, self.callbackDynamic) _ = rospy.Subscriber("/uav1/odometry/gps_local_odom", Odometry, self.callbackStatic) ############# Mapping # # _ = rospy.Subscriber("/build_map3D", PoseArray, self.callbackBuildMap) _ = rospy.Subscriber("/uav1/velodyne/scan", PointCloud2, self.callbackBuildMap3D) # _ = rospy.Subscriber("/zed/cloud_map", PointCloud2, self.callbackBuildMapZed3D) # _ = rospy.Subscriber("/orb_slam2_rgbd/map_points", PointCloud2, self.callbackBuildMap3DOrbs) # _ = rospy.Subscriber("/orbslam/filtered/map_points", PointCloud2, self.callbackBuildMap3DOrbsFiltered) # _ = rospy.Subscriber("/hokuyo20/laser/scan", LaserScan, self.callbackHokuyo20) # _ = rospy.Subscriber("/hokuyo/laser/scan", LaserScan, self.callbackHokuyo) # # _ = rospy.Subscriber("/build_map", PoseArray, self.callbackBuildMap2D) # decolagemInicial() print("Espere um momento, ja iremos comecar") rospy.sleep(1) self.unic["SM"] = 1 self.memoria["inicial"] = memory_usage() self.cpu["inicial"] = psutil.cpu_percent() # set_vio() # ---------------------------- Loop :3 ---------------------------------- def callbackMain(self, odom): if self.unic["SM"] == 1 and self.unic["definirRota"] == 1: self.rotinaNormal() # ---------------------------- Bateria ---------------------------------- def callbackBattery(self, bat): self.bateria["atual"] = bat.current if self.unic["bateria"] == 0: self.bateria["inicial"] = bat.current self.unic["bateria"] = 1 self.counts["total"] = time() if self.unic["bateria"] == 2: self.bateria["final"] = bat.current self.bateria["uso"] = self.bateria["final"] - self.bateria["inicial"] self.unic["bateria"] = 4 def callbackBatteryGazebo(self, bat): self.bateriaGazebo["atual"] = bat.data if self.unic["bateriaGazebo"] == 0: self.bateriaGazebo["inicial"] = bat.data self.unic["bateriaGazebo"] = 1 if self.unic["bateriaGazebo"] == 2: print(bat.data) self.bateriaGazebo["final"] = bat.data self.bateriaGazebo["uso"] = self.bateriaGazebo["final"] - self.bateriaGazebo["inicial"] # self.unic["bateriaGazebo"] = 4 # ---------------------------- Construir Mapa ---------------------------------- def callbackLaser(self, alt): self.alturaLaser = alt.range # ---------------------------- Obstaculo Dinamico ---------------------------------- def callbackDynamic(self, odom): # print("Obstaculo dinamico") v1x, v1y, v1z, v1all, v2x, v2y, v2z, v2all = [], [], [], [], [], [], [], [] # Criar um topico com amostragem dos obstaculos em X (0.5) # Restringir a visao para a direcao em q o drone esta indo # checagem a cada 2 tempos # Delimitar um range, como 5-8 metros # identificar se o obs eh dinamico ou n ########## COMO FAZER ########## ########## 2D ########## # checar se ha obs ond antes n tinha e se n tem ond antes tinha # isso ta melhor explicado no slide da quali ########## 3D ########## # checar se o obstaculo esta se aproximando em do UAV entre os dois tempos ########## END ########## # faz a suavizacao com: o ponto atual (0.5 a frente), dois ponto a frente (1 metros), o pseudo ponto de colisao e o ponto destino # ponto destino sera 4-6 (2 a 3 metros) pontos a frente do ponto de colisao # pegar a parte da trajetoria apos o ponto destino # substituir apenas essa parte da trajetoria # checar se tem uma colisao com obstaculo dinamico # atualziar trajetoria ehDym = 0 obsX, obsY, obsZ = [], [], [] if self.checkDym: for i in range(len(self.ABC)): v1, v2, v3 = self.ABC[i], self.ABC1[i], self.ABC2[i] if v1 in self.ABC: self.ABC.remove(v1) if v1 in self.ABC1: self.ABC1.remove(v1) if v1 in self.ABC2: self.ABC2.remove(v1) if v2 in self.ABC: self.ABC.remove(v2) if v2 in self.ABC1: self.ABC1.remove(v2) if v2 in self.ABC2: self.ABC2.remove(v2) if v3 in self.ABC: self.ABC.remove(v3) if v3 in self.ABC1: self.ABC1.remove(v3) if v3 in self.ABC2: self.ABC2.remove(v3) s01, s02 = 0, 0 s11, s12 = 0, 0 s21, s22 = 0, 0 for i in self.ABC: s01 += i[0] s02 += i [1] for i in self.ABC1: s11 += i[0] s12 += i [1] for i in self.ABC2: s21 += i[0] s22 += i [1] direcao = 0 # 1: esquerda | 2: direita | 3: frente | 4: tras if s21 > s11 and s21 > s01: direcao = 1 ehDym = 1 if s21 < s11 and s21 < s01: direcao = 2 ehDym = 1 if s22 > s12 and s22 > s02: direcao = 3 ehDym = 1 if s22 < s12 and s22 < s02: direcap = 4 ehDym = 1 if ehDym: distanciaBase = float("inf") for i in self.ABC: value = dist_euclidiana3D(i[0], i[1], i[2], self.currentPosX, self.currentPosY, self.currentPosZ) if value < distanciaBase: pontoColisao = i distanciaBase = value for ox, oy, oz in zip(obsX, obsY, obsZ): if colidirTrajetoria3D(self.newA2, self.newB2, self.newC2, self.rotas["x"], self.rotas["y"], self.rotas["z"], self.pos): pontoColisao = [ox, oy, oz] self.rotas["x"] = np.concatenate((self.rotas["x"][:self.pos], [pontoColisao[0]] , self.rotas["x"][self.pos+3:]), axis=0) self.rotas["y"] = np.concatenate((self.rotas["y"][:self.pos], [pontoColisao[1]] , self.rotas["y"][self.pos+3:]), axis=0) self.rotas["z"] = np.concatenate((self.rotas["z"][:self.pos], [pontoColisao[2]] , self.rotas["z"][self.pos+3:]), axis=0) newPoints = generate_curve(self.rotas["x"], self.rotas["y"], self.rotas["z"]) self.rotas["x"], self.rotas["y"], self.rotas["z"] = newPoints[:][0], newPoints[:][1], newPoints[:][2] self.rotas["yaw"] = np.array([0] * len(self.rotas["x"])) if pontoColisao in self.abc: self.abc.remove(pontoColisao) self.a, self.b, self.c = [], [], [] for value in self.abc: self.a.append(value[0]) self.b.append(value[1]) self.c.append(value[2]) self.a, self.b, self.c = rotaToGazebo3D(self.rotas["x"], self.rotas["y"], self.rotas["z"], self.a, self.b, self.c) ehDym = 0 self.checkDym = 0 # ---------------------------- Obstaculo Estatico ---------------------------------- def callbackStatic(self, odom): # checar se tem colisao com obstaculo estatico # atualziar trajetoria if ((time() - self.counts["total"]) > 5) and (self.unic["definirRota"] == 1) and (self.avoidStatic == 0 or self.avoidStatic + 6 < self.pos) and (self.pos > 0): if abs(self.currentPosX - self.p.xt) > 4 and abs(self.currentPosY - self.p.yt) > 3 and abs(self.currentPosZ - self.p.yt) > 1: posicao = self.pos # tamanho = len(self.rotas["x"]) # print("VAI CHECAR COLISAO") if colidirTrajetoria3D(self.a, self.b, self.c, self.rotas["x"], self.rotas["y"], self.rotas["z"], posicao, value=0.3): print("Tem colisao na trajetoria") self.rotas["x"] = np.insert(self.rotas["x"],self.pos+1, self.hover) self.rotas["y"] = np.insert(self.rotas["y"],self.pos+1, self.hover) self.rotas["z"] = np.insert(self.rotas["z"],self.pos+1, self.hover) self.rotas["yaw"] = np.insert(self.rotas["yaw"],self.pos+1, self.hover) print("1------1------1") print(self.currentPosX) print(self.currentPosY) print(self.pos) _, t, rx, ry, rz = alg.run(show=0, vmx=self.a, vmy=self.b, vmz=self.c, startx=self.currentPosX, starty=self.currentPosY, startz=self.currentPosZ, p1=self.p, pseudox=self.rotas["x"][self.pos+1:], pseudoy=self.rotas["y"][self.pos+1:], pseudoz=self.rotas["z"][self.pos+1:]) print("2") rx, ry, rz = rotaToGazebo3D(rx, ry, rz, self.a, self.b, self.c, self.distNodes) print("Tempo para recalcular foi de: " + str(t)) self.rotas["x"] = np.concatenate((self.rotas["x"][:posicao-1], np.clip(rx, 0.7, 19.3).tolist()), axis=0)#[self.pos:] = rx self.rotas["y"] = np.concatenate((self.rotas["y"][:posicao-1], np.clip(ry, 0.7, 9.3).tolist()), axis=0)#[self.pos:] = rx self.rotas["z"] = np.concatenate((self.rotas["z"][:posicao-1], np.clip(rz, 0.8, 14).tolist()), axis=0)#[self.pos:] = rx # [self.altura] * len(rx) self.rotas["yaw"] = [self.anguloGeral] * len(self.rotas["x"]) # self.pos = posicao + ((self.pos - posicao) * 2) self.trajetoriaCalculada = 1 # print(self.rotas["x"]) self.variaveisLog["tt"].append(t) # self.counts["total"] = time() print(rx) print(ry) print("-------------") print(self.rotas["x"]) print(self.rotas["y"]) print(self.rotas["z"]) self.avoidStatic = self.pos # ax = plt.axes(projection = "3d") # ax.plot3D(self.a, self.b, self.c, 'k.') # ax.plot3D(self.rotas["x"], self.rotas["y"], self.rotas["z"], 'y.') # ax.plot3D([self.currentPosX], [self.currentPosY], [self.currentPosZ], ".r") # ax.set_xlim(0,20) # ax.set_ylim(0,10) # ax.set_zlim(0,6) # plt.pause(0.01) # plt.show() # else: # print("not") # ---------------------------- Altura Laser ---------------------------------- def callbackBuildMap2D(self, obs): buildMapX, buildMapY = [], [] for value in obs.poses: if dist_euclidiana(self.currentPosX, self.currentPosY, value.position.x, value.position.y) < self.distanciaObsPerto: buildMapX.append(value.position.x) buildMapY.append(value.position.y) # a,b = com capa | a1,b1 = sem capa self.localX, self.localY, _, _, self.localXY = laserROS(buildMapX, buildMapY, self.localX, self.localY, self.localXY, tamCapa=0) def callbackGPSRTK(self, data): if self.unic["gpsrtk"] == 0: self.zero["rtkx"] = data.latitude self.zero["rtky"] = data.longitude self.zero["rtkz"] = data.altitude else: self.currentPosX = haversine([self.zero["rtkx"], self.zero["rtky"]], [self.zero["rtkx"], data.longitude])*1000 if data.latitude < self.zero["rtkx"]: self.currentPosX *= -1 self.currentPosY = haversine([self.zero["rtkx"], self.zero["rtky"]], [data.latitude, self.zero["rtky"]])*1000 if data.longitude < self.zero["rtky"]: self.currentPosY *= -1 self.currentPosZ = data.altitude - self.zero["rtkz"] def rotationMatrix(self, psi0, x1, y1, z1): r = [[np.cos(psi0), np.sin(psi0) * -1, 0], [np.sin(psi0), np.cos(psi0), 0], [0, 0, 1]] pos_local = np.dot(np.transpose(np.asarray(r)), np.asarray([x1, y1, z1])) return pos_local def callbackBuildMap3DOrbsFiltered(self, data): if self.velodyne: gen = point_cloud2.read_points(data, skip_nans=True) int_data = list(gen) a, b, c = [], [], [] for x in int_data: if round(x[2] > -1): a.append(round(x[0])) b.append(round(-x[1])) c.append(round(x[2])) pl = self.rotationMatrix(self.currentPosYaw, a, b, c) a, b, c = [], [], [] for i1, i2, i3 in zip(pl[0], pl[1], pl[2]): if [round(i1), round(i2), round(i3)] not in self.abc: a.append(round(i2+3)) b.append(round(i1+1)) c.append(round(i3+2)) self.a.append(round(i2+3)) self.b.append(round(i1+1)) self.c.append(round(i3+2)) self.abc.append([round(i1), round(i2), round(i3)]) if self.unic["definirRota"] == 0: _, t, rx, ry, rz = alg.run(show=0, vmx=self.a, vmy=self.b, vmz=self.c, startx=self.currentPosX, starty=self.currentPosY, startz=self.currentPosZ, p1=self.p) rx, ry, rz = rotaToGazebo3D(rx, ry, rz, self.a, self.b, self.c, self.distNodes) self.rotas["x"] = np.array(rx) self.rotas["y"] = np.array(ry) self.rotas["z"] = np.array(rz) # [self.altura] * len(rx) self.rotas["yaw"] = np.array([self.anguloGeral] * len(rx)) print("rota definida") self.variaveisLog["tt"].append(t) # ax = plt.axes(projection = "3d") # ax.plot3D(self.a, self.b, self.c, 'k.') # ax.plot3D(self.rotas["x"], self.rotas["y"], self.rotas["z"], 'y.') # ax.plot3D([self.currentPosX], [self.currentPosY], [self.currentPosZ], ".r") # ax.set_zlim(0,4) # plt.pause(0.01) # plt.show() self.unic["definirRota"] = 1 self.velodyne = 0 def callbackBuildMap3DOrbs(self, data): if self.velodyne: gen = point_cloud2.read_points(data, skip_nans=True) int_data = list(gen) a, b, c = [], [], [] for x in int_data: if round(x[2] > 0): a.append(round(x[0])) b.append(round(-x[1])) c.append(round(x[2])) pl = self.rotationMatrix(-math.pi/4, a, b, c) a, b, c = [], [], [] for i1, i2, i3 in zip(pl[0], pl[1], pl[2]): if [round(i1), round(i2), round(i3)] not in self.abc: a.append(round(i2+3)) b.append(round(i1+3)) c.append(round(i3+1)) self.a.append(round(i2+3)) self.b.append(round(i1+3)) self.c.append(round(i3+1)) self.abc.append([round(i1), round(i2), round(i3)]) # if self.currentPosX > 15 and self.currentPosY > 12 and self.currentPosZ > 1 and self.currentPosX < 20 and self.currentPosY < 15: # ax = plt.axes(projection = "3d") # ax.plot3D(self.a, self.b, self.c, 'k.') # ax.plot3D(self.rotas["x"], self.rotas["y"], self.rotas["z"], 'y.') # ax.plot3D([self.currentPosX], [self.currentPosY], [self.currentPosZ], ".r") # ax.set_xlim(-10,100) # ax.set_ylim(-10,100) # ax.set_zlim(0,4) # plt.pause(0.01) # plt.show() self.velodyne = 0 # def callbackHokuyo(self, data): # x, y, z = [], [], [] # for index, value in enumerate(data.ranges[120:600]): # if value < 30: # aux = np.linspace(180, 0, 600-120) # theta = aux[index] # x.append(np.cos(np.radians(theta)) * value) # y.append(np.sin(np.radians(theta)) * value) # z.append(self.currentPosZ) # pl = rotationMatrix3D(self.currentPosYaw, x, y, z, "yaw") # for i1, i2, i3 in zip(pl[0], pl[1], pl[2]): # if [round(i1), round(i2), round(i3)] not in self.abc: # self.a.append(round(i1)) # self.b.append(round(i2)) # self.c.append(round(i3)) # self.abc.append([round(i1), round(i2), round(i3)]) def callbackHokuyo(self, data): for index, value in enumerate(data.ranges[240:720-240]): if value < 15: aux = np.linspace(90, 0, 720-480) theta = aux[index] if self.countDym == 0: self.newA.append(np.cos(np.radians(theta)) * value) self.newB.append(np.sin(np.radians(theta)) * value) self.newC.append(self.currentPosZ) elif self.countDym == 1: self.newA1.append(np.cos(np.radians(theta)) * value) self.newB1.append(np.sin(np.radians(theta)) * value) self.newC1.append(self.currentPosZ) else: self.newA2.append(np.cos(np.radians(theta)) * value) self.newB2.append(np.sin(np.radians(theta)) * value) self.newC2.append(self.currentPosZ) if self.countDym == 0: pl = rotationMatrix3D(self.currentPosYaw, self.newA, self.newB, self.newC, "yaw") self.newA = pl[0] self.newB = pl[1] self.newC = pl[2] elif self.countDym == 1: pl = rotationMatrix3D(self.currentPosYaw, self.newA1, self.newB1, self.newC1, "yaw") self.newA1 = pl[0] self.newB1 = pl[1] self.newC1 = pl[2] else: pl = rotationMatrix3D(self.currentPosYaw, self.newA2, self.newB2, self.newC2, "yaw") self.newA2 = pl[0] self.newB2 = pl[1] self.newC2 = pl[2] self.countDym += 1 if self.countDym == 3: for i1, i2, i3 in zip(pl[0], pl[1], pl[2]): if [round(i1), round(i2), round(i3)] not in self.abc: self.a.append(round(i1)) self.b.append(round(i2)) self.c.append(round(i3)) self.abc.append([round(i1), round(i2), round(i3)]) self.countDym = 0 self.checkDym = 1 self.newA, self.newB, self.newC, self.newA1, self.newB1, self.newC1, self.newA2, self.newB2, self.newC2 = [], [], [], [], [], [], [], [], [] def callbackHokuyo20(self, data): a, b, c = [], [], [] for index, value in enumerate(data.ranges[120:600]): if value < 30: aux = np.linspace(180, 0, 600-120) theta = aux[index] a.append(np.cos(np.radians(theta)) * value) b.append(np.sin(np.radians(theta)) * value) c.append(self.currentPosZ) pl = rotationMatrix3D(self.currentPosYaw, a, b, c, "yaw") pl = rotationMatrix3D(math.radians(-20), pl[0], pl[1], pl[2], "pitch") for i1, i2, i3 in zip(pl[0], pl[1], pl[2]): if [round(i1), round(i2), round(i3)] not in self.abc: self.a.append(round(i1)) self.b.append(round(i2)) self.c.append(round(i3)) self.abc.append([round(i1), round(i2), round(i3)]) # if self.currentPosX > 15 and self.currentPosY > 12 and self.currentPosZ > 1 and self.currentPosX < 20 and self.currentPosY < 15: # print(time() - self.contadorTotal) # if 400 > time() - self.contadorTotal > 20: # ax = plt.axes(projection = "3d") # ax.plot3D(self.a, self.b, self.c, 'k.') # ax.plot3D(self.rotas["x"], self.rotas["y"], self.rotas["z"], 'y.') # ax.plot3D([self.currentPosX], [self.currentPosY], [self.currentPosZ], ".r") # ax.set_xlim(0,20) # ax.set_ylim(0,10) # ax.set_zlim(0,4) # plt.pause(0.01) # plt.show() def callbackBuildMapZed3D(self, data): gen = point_cloud2.read_points(data, skip_nans=True) int_data = list(gen) self.newA, self.newB, self.newC = [], [], [] for x in int_data: if round(x[2] > 0): self.newA.append(round(x[0])) self.newB.append(round(-x[1])) self.newC.append(round(x[2])) pl = self.rotationMatrix(0, self.newA, self.newB, self.newC) self.newA, self.newB, self.newC = [], [], [] for i1, i2, i3 in zip(pl[0], pl[1], pl[2]): dentroRange = 1 if dentroRange: if [round(i1), round(i2), round(i3)] not in self.abc and round(i2)>1: self.newA.append(round(i2)) self.newB.append(round(i1)) self.newC.append(round(i3+1)) self.a.append(round(i2)) self.b.append(round(i1)) self.c.append(round(i3+1)) self.abc.append([round(i1), round(i2), round(i3)]) if self.unic["definirRota"] == 0: print("Iniciando a definir rota") _, t, rx, ry, rz = alg.run(show=0, vmx=self.a, vmy=self.b, vmz=self.c, startx=self.currentPosX, starty=self.currentPosY, startz=self.currentPosZ, p1=self.p) rx, ry, rz = rotaToGazebo3D(rx, ry, rz, self.a, self.b, self.c, self.distNodes) self.rotas["x"] = np.array(rx) self.rotas["y"] = np.array(ry) self.rotas["z"] = np.array(rz) # [self.altura] * len(rx) self.rotas["yaw"] = np.array([self.anguloGeral] * len(rx)) ax = plt.axes(projection = "3d") ax.plot3D(self.a, self.b, self.c, 'k.') ax.plot3D(self.rotas["x"], self.rotas["y"], self.rotas["z"], 'y.') ax.plot3D([self.currentPosX], [self.currentPosY], [self.currentPosZ], ".r") ax.set_xlim(0,20) ax.set_ylim(0,10) ax.set_zlim(0,6) plt.pause(0.01) plt.show() # print(self.a) # print(self.b) # print(self.c) print("rota definida") self.unic["definirRota"] = 1 def callbackBuildMap3D(self, data): if self.velodyne: if not self.knownEnvironment: gen = point_cloud2.read_points(data, skip_nans=True) int_data = list(gen) self.newA, self.newB, self.newC = [], [], [] for x in int_data: if round(x[2] >= 0): self.newA.append(round(x[0])) self.newB.append(round(x[1])) self.newC.append(round(x[2])) # self.newA.append(x[0]) # self.newB.append(x[1]) # self.newC.append(x[2]) pl = self.rotationMatrix(self.currentPosYaw, self.newA, self.newB, self.newC) self.newA, self.newB, self.newC = [], [], [] # print("Virar para: " + str(math.degrees(self.rand))) # print("Angulo superior: " + str(math.degrees(randSup))) # print("Angulo inferior: " + str(math.degrees(randInf))) for i1, i2, i3 in zip(pl[0], pl[1], pl[2]): dentroRange = 1 if dentroRange: if [round(i1), round(i2), round(i3)] not in self.abc and round(i2)>1: self.newA.append(round(i2+3)) self.newB.append(round(i1+3)) self.newC.append(round(i3+1)) self.a.append(round(i2+3)) self.b.append(round(i1+3)) self.c.append(round(i3+1)) self.abc.append([round(i1), round(i2), round(i3)]) else: self.a = self.p.xobs self.b = self.p.xobs self.c = self.p.xobs if self.unic["definirRota"] == 0: print("Iniciando a definir rota") _, t, rx, ry, rz = alg.run(show=0, vmx=self.a, vmy=self.b, vmz=self.c, startx=self.currentPosX, starty=self.currentPosY, startz=self.currentPosZ, p1=self.p) rx, ry, rz = rotaToGazebo3D(rx, ry, rz, self.a, self.b, self.c, self.distNodes) self.rotas["x"] = np.array(rx) self.rotas["y"] = np.array(ry) self.rotas["z"] = np.array(rz) # [self.altura] * len(rx) self.rotas["yaw"] = np.array([self.anguloGeral] * len(rx)) # print(self.a) # print(self.b) # print(self.c) # ax = plt.axes(projection = "3d") # ax.plot3D(self.a, self.b, self.c, 'k.') # ax.plot3D(self.rotas["x"], self.rotas["y"], self.rotas["z"], 'y.') # ax.plot3D([self.currentPosX], [self.currentPosY], [self.currentPosZ], ".r") # ax.set_xlim(0,20) # ax.set_ylim(0,10) # ax.set_zlim(0,6) # plt.pause(0.01) # plt.show() print("rota definida") self.unic["definirRota"] = 1 self.velodyne = 0 def callbackBuildMap(self, obs): buildMapX, buildMapY, buildMapZ = [], [], [] for value in obs.poses: buildMapX.append(value.position.x) buildMapY.append(value.position.y) buildMapZ.append(value.position.z) if len(buildMapX) > 5: # if self.trocaYaw: for v1, v2, v3 in zip(buildMapX, buildMapY, buildMapZ): self.a.append(v1) self.b.append(v2) self.c.append(v3) print(time() - self.counts["total"]) # if round(time() - self.counts["total"])%1==0 and 24 > time() - self.counts["total"] > 15: # fig = plt.figure() # ax = fig.add_subplot(111, projection='3d') # zz = [2] * len(self.xx) # ax.plot3D(self.xx, self.yy, zz, ".g") # ax.plot3D([self.currentPosX], [self.currentPosY], [self.currentPosZ], ".r") # ax.plot3D(self.a, self.b, self.c,".k") # ax.plot3D(buildMapX, buildMapY, buildMapZ,".y") # ax.set_title(self.currentPosYaw) # ax.set_xlabel("x (m)" + str(self.currentPosX)) # ax.set_ylabel("y (m)" + str(self.currentPosY)) # ax.set_zlabel("z (m)" + str(self.currentPosZ)) # ax.set_xlim(-50, 100) # ax.set_ylim(-50, 100) # ax.set_zlim(-3, 7) # ax.view_init(73, -159) # self.contador += 1 # plt.show() # ---------------------------- Onde o UAV ta ---------------------------------- def callbackPosicao(self, odom): _, _, yaw = euler_from_quaternion([odom.pose.pose.orientation.x, odom.pose.pose.orientation.y, odom.pose.pose.orientation.z, odom.pose.pose.orientation.w]) if yaw < 0: yaw = math.pi + yaw # print("-------------------") # print(odom.pose) if self.unic["gpsrtk"] == 0: self.currentPosX = odom.pose.pose.position.x self.currentPosY = odom.pose.pose.position.y self.currentPosZ = odom.pose.pose.position.z self.currentPosYaw = yaw # ---------------------------- State Machine ---------------------------------- def rotinaNormal(self): if self.unic["SM"] == 1: # Se tiver funcionando # ---------------- Decidindo sua vida --------------------- if self.status == self.arrived: self.unic["idle"] = 0 # ---------------- Cabou --------------------- if ((abs(self.currentPosX - self.rotas["x"][-1]) < 0.2 and abs(self.currentPosY - self.rotas["y"][-1]) < 0.2 and abs(self.currentPosZ - self.rotas["z"][-1]) < 0.6) or(self.pos == len(self.rotas["x"]))) and self.unic["definirRota"]==1: # if self.pos == len(self.rotas["x"]): if self.unic["bateria"]!= 4: self.unic["bateria"] = 2 if self.unic["bateriaGazebo"] == 1: self.unic["bateriaGazebo"] = 2 self.memoria["final"] = memory_usage() self.cpu["final"] = psutil.cpu_percent() print(self.rotas["x"]) print(self.rotas["y"]) print(self.rotas["z"]) print("Uso da bateria:") print(self.bateria) print("Uso da bateria Gazebo:") self.bateriaGazebo["uso"] = self.bateriaGazebo["inicial"] - self.bateriaGazebo["atual"] print(self.bateriaGazebo) print("Comprimento: " + str(distancia_rota(self.rotas["x"], self.rotas["y"]))) try: print("Media do tempo: " + str(stc.mean(self.variaveisLog["tt"]))) print("Variancia do tempo: " + str(stc.variance(self.variaveisLog["tt"]))) print("Desvio padrao do tempo: " + str(stc.stdev(self.variaveisLog["tt"]))) except: pass try: print("Maior do tempo: " + str(max(self.variaveisLog["tt"]))) print("Menor do tempo: " + str(min(self.variaveisLog["tt"]))) except: pass print("Tempo de voo: " + str(time() - self.counts["total"])) print("CPU:") print(self.cpu) print("Memoria:") print(self.memoria) print("CPU Real:") self.cpu["inicial"] *= self.processadorDoPc / 100 self.cpu["final"] *= self.processadorDoPc / 100 self.cpu["uso"] *= self.cpu["final"] - self.cpu["inicial"] print(self.cpu) print("Memoria Real:") self.memoria["inicial"] *= self.memoriaDoPc / 100 self.memoria["final"] *= self.memoriaDoPc / 100 self.memoria["uso"] *= self.memoria["final"] - self.memoria["inicial"] print(self.memoria) if self.log: self.f.write("Uso da bateria:") self.f.write(self.bateria) self.f.write("Uso da bateria Gazebo:") self.f.write(self.bateriaGazebo) self.f.write("Comprimento: " + str(distancia_rota(self.rotas["x"], self.rotas["y"]))) self.f.write("Media do tempo: " + str(stc.mean(self.variaveisLog["tt"]))) try: self.f.write("Variancia do tempo: " + str(stc.variance(self.variaveisLog["tt"]))) self.f.write("Desvio padrao do tempo: " + str(stc.stdev(self.variaveisLog["tt"]))) except: pass self.f.write("Maior do tempo: " + str(max(self.variaveisLog["tt"]))) self.f.write("Menor do tempo: " + str(min(self.variaveisLog["tt"]))) self.f.write("Tempo de voo: " + str(time() - self.counts["total"])) self.f.write("Trajetoria X") for value in self.rotas["x"]: self.f.write(str(value)) self.f.write(", ") self.f.write("\n\n") print("Trajetoria Y") for value in self.rotas["y"]: self.f.write(str(value)) self.f.write(", ") self.f.write("\n\n") print("Trajetoria Z") for value in self.rotas["z"]: self.f.write(str(value)) self.f.write(", ") self.f.write("\n\n") print("Acabou a missao") self.unic["SM"] = 0 exit() try: # ---------------- Flag Start/End --------------------- if self.rotas["x"][self.pos] == self.land: self.unic["print"] = logStateMachine("Landing", self.unic["print"]) self.tempo["wait"] = self.tempo["land"] land() elif self.rotas["x"][self.pos] == self.takeoff: self.unic["print"] = logStateMachine("Take off", self.unic["print"]) self.tempo["wait"] = self.tempo["takeoff"] takeoff() # ---------------- Flag Tempo --------------------- elif self.rotas["x"][self.pos] == self.hover: self.unic["print"], self.unic["hover"] = logStateMachine("Hover", self.unic["print"], self.unic["hover"]) self.tempo["wait"] = self.tempo["hover"] elif self.rotas["x"][self.pos] == self.sec: self.unic["print"], self.unic["sec"] = logStateMachine("Wait a second", self.unic["print"], self.unic["sec"]) self.tempo["wait"] = self.tempo["sec"] elif self.rotas["x"][self.pos] == self.esperarCamera: self.unic["print"], self.unic["esperarCamera"] = logStateMachine("Waiting Camera", self.unic["print"], self.unic["esperarCamera"]) self.tempo["wait"] = self.tempo["esperarCamera"] # ---------------- Flag Visao --------------------- elif self.rotas["x"][self.pos] == self.calibrarTarget: self.unic["print"] = logStateMachine("Calibrating Target", self.unic["print"]) self.tempo["wait"] = self.tempo["calibrarTarget"] self.unic["calibrarTarget"] = 1 # ---------------- Puedo Caminar --------------------- else: print("Estou em") print(str(round(self.currentPosX, 2)) + " - " + str(round(self.currentPosY, 2)) + " - " + str(round(self.currentPosZ, 2))) print("Indo para") print(str(round(self.rotas["x"][self.pos], 2)) + " - " + str(round(self.rotas["y"][self.pos], 2)) + " - " + str(round(self.rotas["z"][self.pos], 2))) self.rand = rotacionar(self.currentPosX, self.currentPosY, self.rotas["x"][self.pos], self.rotas["y"][self.pos]) self.unic["print"], self.unic["andar"] = logStateMachine("Walking", self.unic["print"], self.unic["andar"]) acrZ = 0#-0.6 if self.rotas["z"][self.pos-1] > self.rotas["z"][self.pos] else 0.8 self.tempo["wait"] = andarGlobal(self.rotas["x"][self.pos], self.rotas["y"][self.pos], self.rotas["z"][self.pos] + acrZ, self.rotas["yaw"][self.pos], self.currentPosX, self.currentPosY, self.currentPosZ, self.currentPosYaw, rotacao=False, MPC=self.controller) self.velodyne = 1 except: pass if self.unic["SM"] == 1: self.counts["tempo"] = time() self.status = self.busy # ---------------- UAV ocupado --------------------- if self.status == self.busy: self.unic["print"] = 0 self.unic["busy"] = logStateMachine("I am busy", self.unic["busy"]) if self.unic["hover"]: if time() - self.counts["tempo"] > self.tempo["wait"] - 1 and self.trajetoriaCalculada==0 and self.addRota==0: if abs(self.currentPosX - self.p.xt) > 0.5 and abs(self.currentPosY - self.p.yt) > 0.5 and abs(self.currentPosZ - self.p.yt) > 0.8: self.rotas["x"] = np.insert(self.rotas["x"],self.pos+1, self.hover) self.rotas["y"] = np.insert(self.rotas["y"],self.pos+1, self.hover) self.rotas["z"] = np.insert(self.rotas["z"],self.pos+1, self.hover) self.rotas["yaw"] = np.insert(self.rotas["yaw"],self.pos+1, self.hover) self.addRota = 1 if time() - self.counts["tempo"] > self.tempo["wait"] and self.trajetoriaCalculada: self.trajetoriaCalculada = 0 if time() - self.counts["tempo"] > self.tempo["wait"]: self.addRota = 0 self.status = self.idle self.counts["parar"] = time() # ---------------- UAV mudando de estado --------------------- if self.status == self.idle: if self.unic["hover"] == 1: self.unic["hover"] = 0 if self.unic["sec"] == 1: self.unic["sec"] = 0 # checar se realmente foi para o ponto desejado, se nao tentar de novo # if self.unic["andar"] == 1: # print(self.rotas["x"]) # if dist_euclidiana([self.currentPosX, self.currentPosY], [self.rotas["x"][self.pos], self.rotas["y"][self.pos]]) > 0.25: # addRotaPonto(self.pos+1, self.rotas["x"][self.pos], self.rotas["y"][self.pos], self.rotas["x"], self.rotas["y"], self.rotas["z"], self.rotas["yaw"], self.rotas["z"][self.pos], self.rotas["yaw"][self.pos]) # self.unic["andar"] = 0 self.unic["busy"] = 0 self.unic["idle"] = logStateMachine("Idle", self.unic["idle"]) if time() - self.counts["parar"] > self.tempo["parar"]: print(self.pos) print(len(self.rotas["x"])) self.status = self.arrived self.pos += 1 def main(): rospy.init_node("Planejador") globalPlanner() # plt.show() try: rospy.spin() except rospy.ROSInterruptException: pass # plt.show() if __name__ == "__main__": main()
[ "rospy.Subscriber", "matplotlib.pyplot.axes", "haversine.haversine", "numpy.clip", "numpy.sin", "statistics.variance", "helper.ambiente.Pontos", "sensor_msgs.point_cloud2.read_points", "math.radians", "numpy.insert", "rospy.init_node", "numpy.linspace", "matplotlib.pyplot.pause", "datetime...
[((45755, 45784), 'rospy.init_node', 'rospy.init_node', (['"""Planejador"""'], {}), "('Planejador')\n", (45770, 45784), False, 'import rospy\n'), ((2540, 2548), 'helper.ambiente.Pontos', 'Pontos', ([], {}), '()\n', (2546, 2548), False, 'from helper.ambiente import Pontos\n'), ((6062, 6136), 'rospy.Subscriber', 'rospy.Subscriber', (['"""/uav1/odometry/odom_local"""', 'Odometry', 'self.callbackMain'], {}), "('/uav1/odometry/odom_local', Odometry, self.callbackMain)\n", (6078, 6136), False, 'import rospy\n'), ((6184, 6260), 'rospy.Subscriber', 'rospy.Subscriber', (['"""/uav1/odometry/odom_main"""', 'Odometry', 'self.callbackPosicao'], {}), "('/uav1/odometry/odom_main', Odometry, self.callbackPosicao)\n", (6200, 6260), False, 'import rospy\n'), ((6651, 6722), 'rospy.Subscriber', 'rospy.Subscriber', (['"""/battery/percent"""', 'Int32', 'self.callbackBatteryGazebo'], {}), "('/battery/percent', Int32, self.callbackBatteryGazebo)\n", (6667, 6722), False, 'import rospy\n'), ((6879, 6964), 'rospy.Subscriber', 'rospy.Subscriber', (['"""/uav1/odometry/gps_local_odom"""', 'Odometry', 'self.callbackStatic'], {}), "('/uav1/odometry/gps_local_odom', Odometry, self.callbackStatic\n )\n", (6895, 6964), False, 'import rospy\n'), ((7085, 7162), 'rospy.Subscriber', 'rospy.Subscriber', (['"""/uav1/velodyne/scan"""', 'PointCloud2', 'self.callbackBuildMap3D'], {}), "('/uav1/velodyne/scan', PointCloud2, self.callbackBuildMap3D)\n", (7101, 7162), False, 'import rospy\n'), ((7818, 7832), 'rospy.sleep', 'rospy.sleep', (['(1)'], {}), '(1)\n', (7829, 7832), False, 'import rospy\n'), ((7940, 7960), 'psutil.cpu_percent', 'psutil.cpu_percent', ([], {}), '()\n', (7958, 7960), False, 'import psutil\n'), ((27526, 27572), 'sensor_msgs.point_cloud2.read_points', 'point_cloud2.read_points', (['data'], {'skip_nans': '(True)'}), '(data, skip_nans=True)\n', (27550, 27572), False, 'from sensor_msgs import point_cloud2\n'), ((34445, 34593), 'tf.transformations.euler_from_quaternion', 'euler_from_quaternion', (['[odom.pose.pose.orientation.x, odom.pose.pose.orientation.y, odom.pose.pose\n .orientation.z, odom.pose.pose.orientation.w]'], {}), '([odom.pose.pose.orientation.x, odom.pose.pose.\n orientation.y, odom.pose.pose.orientation.z, odom.pose.pose.orientation.w])\n', (34466, 34593), False, 'from tf.transformations import euler_from_quaternion\n'), ((45839, 45851), 'rospy.spin', 'rospy.spin', ([], {}), '()\n', (45849, 45851), False, 'import rospy\n'), ((3943, 3955), 'numpy.array', 'np.array', (['[]'], {}), '([])\n', (3951, 3955), True, 'import numpy as np\n'), ((3957, 3969), 'numpy.array', 'np.array', (['[]'], {}), '([])\n', (3965, 3969), True, 'import numpy as np\n'), ((3971, 3983), 'numpy.array', 'np.array', (['[]'], {}), '([])\n', (3979, 3983), True, 'import numpy as np\n'), ((3985, 3997), 'numpy.array', 'np.array', (['[]'], {}), '([])\n', (3993, 3997), True, 'import numpy as np\n'), ((19160, 19184), 'numpy.asarray', 'np.asarray', (['[x1, y1, z1]'], {}), '([x1, y1, z1])\n', (19170, 19184), True, 'import numpy as np\n'), ((19308, 19354), 'sensor_msgs.point_cloud2.read_points', 'point_cloud2.read_points', (['data'], {'skip_nans': '(True)'}), '(data, skip_nans=True)\n', (19332, 19354), False, 'from sensor_msgs import point_cloud2\n'), ((21385, 21431), 'sensor_msgs.point_cloud2.read_points', 'point_cloud2.read_points', (['data'], {'skip_nans': '(True)'}), '(data, skip_nans=True)\n', (21409, 21431), False, 'from sensor_msgs import point_cloud2\n'), ((26410, 26427), 'math.radians', 'math.radians', (['(-20)'], {}), '(-20)\n', (26422, 26427), False, 'import math\n'), ((28654, 28795), 'classic.rrt_connect_3d.run', 'alg.run', ([], {'show': '(0)', 'vmx': 'self.a', 'vmy': 'self.b', 'vmz': 'self.c', 'startx': 'self.currentPosX', 'starty': 'self.currentPosY', 'startz': 'self.currentPosZ', 'p1': 'self.p'}), '(show=0, vmx=self.a, vmy=self.b, vmz=self.c, startx=self.currentPosX,\n starty=self.currentPosY, startz=self.currentPosZ, p1=self.p)\n', (28661, 28795), True, 'from classic import rrt_connect_3d as alg\n'), ((28914, 28926), 'numpy.array', 'np.array', (['rx'], {}), '(rx)\n', (28922, 28926), True, 'import numpy as np\n'), ((28957, 28969), 'numpy.array', 'np.array', (['ry'], {}), '(ry)\n', (28965, 28969), True, 'import numpy as np\n'), ((29000, 29012), 'numpy.array', 'np.array', (['rz'], {}), '(rz)\n', (29008, 29012), True, 'import numpy as np\n'), ((29127, 29152), 'matplotlib.pyplot.axes', 'plt.axes', ([], {'projection': '"""3d"""'}), "(projection='3d')\n", (29135, 29152), True, 'import matplotlib.pyplot as plt\n'), ((29480, 29495), 'matplotlib.pyplot.pause', 'plt.pause', (['(0.01)'], {}), '(0.01)\n', (29489, 29495), True, 'import matplotlib.pyplot as plt\n'), ((29508, 29518), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (29516, 29518), True, 'import matplotlib.pyplot as plt\n'), ((18532, 18623), 'haversine.haversine', 'haversine', (["[self.zero['rtkx'], self.zero['rtky']]", "[self.zero['rtkx'], data.longitude]"], {}), "([self.zero['rtkx'], self.zero['rtky']], [self.zero['rtkx'], data.\n longitude])\n", (18541, 18623), False, 'from haversine import haversine\n'), ((18729, 18819), 'haversine.haversine', 'haversine', (["[self.zero['rtkx'], self.zero['rtky']]", "[data.latitude, self.zero['rtky']]"], {}), "([self.zero['rtkx'], self.zero['rtky']], [data.latitude, self.zero\n ['rtky']])\n", (18738, 18819), False, 'from haversine import haversine\n'), ((19023, 19035), 'numpy.cos', 'np.cos', (['psi0'], {}), '(psi0)\n', (19029, 19035), True, 'import numpy as np\n'), ((19061, 19073), 'numpy.sin', 'np.sin', (['psi0'], {}), '(psi0)\n', (19067, 19073), True, 'import numpy as np\n'), ((19075, 19087), 'numpy.cos', 'np.cos', (['psi0'], {}), '(psi0)\n', (19081, 19087), True, 'import numpy as np\n'), ((19144, 19157), 'numpy.asarray', 'np.asarray', (['r'], {}), '(r)\n', (19154, 19157), True, 'import numpy as np\n'), ((20266, 20407), 'classic.rrt_connect_3d.run', 'alg.run', ([], {'show': '(0)', 'vmx': 'self.a', 'vmy': 'self.b', 'vmz': 'self.c', 'startx': 'self.currentPosX', 'starty': 'self.currentPosY', 'startz': 'self.currentPosZ', 'p1': 'self.p'}), '(show=0, vmx=self.a, vmy=self.b, vmz=self.c, startx=self.currentPosX,\n starty=self.currentPosY, startz=self.currentPosZ, p1=self.p)\n', (20273, 20407), True, 'from classic import rrt_connect_3d as alg\n'), ((20534, 20546), 'numpy.array', 'np.array', (['rx'], {}), '(rx)\n', (20542, 20546), True, 'import numpy as np\n'), ((20581, 20593), 'numpy.array', 'np.array', (['ry'], {}), '(ry)\n', (20589, 20593), True, 'import numpy as np\n'), ((20628, 20640), 'numpy.array', 'np.array', (['rz'], {}), '(rz)\n', (20636, 20640), True, 'import numpy as np\n'), ((23870, 23899), 'numpy.linspace', 'np.linspace', (['(90)', '(0)', '(720 - 480)'], {}), '(90, 0, 720 - 480)\n', (23881, 23899), True, 'import numpy as np\n'), ((26086, 26116), 'numpy.linspace', 'np.linspace', (['(180)', '(0)', '(600 - 120)'], {}), '(180, 0, 600 - 120)\n', (26097, 26116), True, 'import numpy as np\n'), ((29842, 29888), 'sensor_msgs.point_cloud2.read_points', 'point_cloud2.read_points', (['data'], {'skip_nans': '(True)'}), '(data, skip_nans=True)\n', (29866, 29888), False, 'from sensor_msgs import point_cloud2\n'), ((31658, 31799), 'classic.rrt_connect_3d.run', 'alg.run', ([], {'show': '(0)', 'vmx': 'self.a', 'vmy': 'self.b', 'vmz': 'self.c', 'startx': 'self.currentPosX', 'starty': 'self.currentPosY', 'startz': 'self.currentPosZ', 'p1': 'self.p'}), '(show=0, vmx=self.a, vmy=self.b, vmz=self.c, startx=self.currentPosX,\n starty=self.currentPosY, startz=self.currentPosZ, p1=self.p)\n', (31665, 31799), True, 'from classic import rrt_connect_3d as alg\n'), ((31926, 31938), 'numpy.array', 'np.array', (['rx'], {}), '(rx)\n', (31934, 31938), True, 'import numpy as np\n'), ((31973, 31985), 'numpy.array', 'np.array', (['ry'], {}), '(ry)\n', (31981, 31985), True, 'import numpy as np\n'), ((32020, 32032), 'numpy.array', 'np.array', (['rz'], {}), '(rz)\n', (32028, 32032), True, 'import numpy as np\n'), ((15049, 15101), 'numpy.insert', 'np.insert', (["self.rotas['x']", '(self.pos + 1)', 'self.hover'], {}), "(self.rotas['x'], self.pos + 1, self.hover)\n", (15058, 15101), True, 'import numpy as np\n'), ((15137, 15189), 'numpy.insert', 'np.insert', (["self.rotas['y']", '(self.pos + 1)', 'self.hover'], {}), "(self.rotas['y'], self.pos + 1, self.hover)\n", (15146, 15189), True, 'import numpy as np\n'), ((15225, 15277), 'numpy.insert', 'np.insert', (["self.rotas['z']", '(self.pos + 1)', 'self.hover'], {}), "(self.rotas['z'], self.pos + 1, self.hover)\n", (15234, 15277), True, 'import numpy as np\n'), ((15315, 15369), 'numpy.insert', 'np.insert', (["self.rotas['yaw']", '(self.pos + 1)', 'self.hover'], {}), "(self.rotas['yaw'], self.pos + 1, self.hover)\n", (15324, 15369), True, 'import numpy as np\n'), ((15575, 15845), 'classic.rrt_connect_3d.run', 'alg.run', ([], {'show': '(0)', 'vmx': 'self.a', 'vmy': 'self.b', 'vmz': 'self.c', 'startx': 'self.currentPosX', 'starty': 'self.currentPosY', 'startz': 'self.currentPosZ', 'p1': 'self.p', 'pseudox': "self.rotas['x'][self.pos + 1:]", 'pseudoy': "self.rotas['y'][self.pos + 1:]", 'pseudoz': "self.rotas['z'][self.pos + 1:]"}), "(show=0, vmx=self.a, vmy=self.b, vmz=self.c, startx=self.currentPosX,\n starty=self.currentPosY, startz=self.currentPosZ, p1=self.p, pseudox=\n self.rotas['x'][self.pos + 1:], pseudoy=self.rotas['y'][self.pos + 1:],\n pseudoz=self.rotas['z'][self.pos + 1:])\n", (15582, 15845), True, 'from classic import rrt_connect_3d as alg\n'), ((19037, 19049), 'numpy.sin', 'np.sin', (['psi0'], {}), '(psi0)\n', (19043, 19049), True, 'import numpy as np\n'), ((35908, 35928), 'psutil.cpu_percent', 'psutil.cpu_percent', ([], {}), '()\n', (35926, 35928), False, 'import psutil\n'), ((39823, 39829), 'sys.exit', 'exit', ([], {}), '()\n', (39827, 39829), False, 'from sys import exit\n'), ((5003, 5017), 'datetime.datetime.now', 'datetime.now', ([], {}), '()\n', (5015, 5017), False, 'from datetime import datetime\n'), ((12858, 12966), 'numpy.concatenate', 'np.concatenate', (["(self.rotas['x'][:self.pos], [pontoColisao[0]], self.rotas['x'][self.pos + 3:])"], {'axis': '(0)'}), "((self.rotas['x'][:self.pos], [pontoColisao[0]], self.rotas[\n 'x'][self.pos + 3:]), axis=0)\n", (12872, 12966), True, 'import numpy as np\n'), ((13003, 13111), 'numpy.concatenate', 'np.concatenate', (["(self.rotas['y'][:self.pos], [pontoColisao[1]], self.rotas['y'][self.pos + 3:])"], {'axis': '(0)'}), "((self.rotas['y'][:self.pos], [pontoColisao[1]], self.rotas[\n 'y'][self.pos + 3:]), axis=0)\n", (13017, 13111), True, 'import numpy as np\n'), ((13148, 13256), 'numpy.concatenate', 'np.concatenate', (["(self.rotas['z'][:self.pos], [pontoColisao[2]], self.rotas['z'][self.pos + 3:])"], {'axis': '(0)'}), "((self.rotas['z'][:self.pos], [pontoColisao[2]], self.rotas[\n 'z'][self.pos + 3:]), axis=0)\n", (13162, 13256), True, 'import numpy as np\n'), ((4974, 4988), 'datetime.datetime.now', 'datetime.now', ([], {}), '()\n', (4986, 4988), False, 'from datetime import datetime\n'), ((26182, 26199), 'numpy.radians', 'np.radians', (['theta'], {}), '(theta)\n', (26192, 26199), True, 'import numpy as np\n'), ((26242, 26259), 'numpy.radians', 'np.radians', (['theta'], {}), '(theta)\n', (26252, 26259), True, 'import numpy as np\n'), ((43747, 43799), 'numpy.insert', 'np.insert', (["self.rotas['x']", '(self.pos + 1)', 'self.hover'], {}), "(self.rotas['x'], self.pos + 1, self.hover)\n", (43756, 43799), True, 'import numpy as np\n'), ((43843, 43895), 'numpy.insert', 'np.insert', (["self.rotas['y']", '(self.pos + 1)', 'self.hover'], {}), "(self.rotas['y'], self.pos + 1, self.hover)\n", (43852, 43895), True, 'import numpy as np\n'), ((43939, 43991), 'numpy.insert', 'np.insert', (["self.rotas['z']", '(self.pos + 1)', 'self.hover'], {}), "(self.rotas['z'], self.pos + 1, self.hover)\n", (43948, 43991), True, 'import numpy as np\n'), ((44037, 44091), 'numpy.insert', 'np.insert', (["self.rotas['yaw']", '(self.pos + 1)', 'self.hover'], {}), "(self.rotas['yaw'], self.pos + 1, self.hover)\n", (44046, 44091), True, 'import numpy as np\n'), ((4947, 4961), 'datetime.datetime.now', 'datetime.now', ([], {}), '()\n', (4959, 4961), False, 'from datetime import datetime\n'), ((24016, 24033), 'numpy.radians', 'np.radians', (['theta'], {}), '(theta)\n', (24026, 24033), True, 'import numpy as np\n'), ((24088, 24105), 'numpy.radians', 'np.radians', (['theta'], {}), '(theta)\n', (24098, 24105), True, 'import numpy as np\n'), ((4919, 4933), 'datetime.datetime.now', 'datetime.now', ([], {}), '()\n', (4931, 4933), False, 'from datetime import datetime\n'), ((16111, 16133), 'numpy.clip', 'np.clip', (['rx', '(0.7)', '(19.3)'], {}), '(rx, 0.7, 19.3)\n', (16118, 16133), True, 'import numpy as np\n'), ((16253, 16274), 'numpy.clip', 'np.clip', (['ry', '(0.7)', '(9.3)'], {}), '(ry, 0.7, 9.3)\n', (16260, 16274), True, 'import numpy as np\n'), ((16394, 16414), 'numpy.clip', 'np.clip', (['rz', '(0.8)', '(14)'], {}), '(rz, 0.8, 14)\n', (16401, 16414), True, 'import numpy as np\n'), ((24257, 24274), 'numpy.radians', 'np.radians', (['theta'], {}), '(theta)\n', (24267, 24274), True, 'import numpy as np\n'), ((24330, 24347), 'numpy.radians', 'np.radians', (['theta'], {}), '(theta)\n', (24340, 24347), True, 'import numpy as np\n'), ((24481, 24498), 'numpy.radians', 'np.radians', (['theta'], {}), '(theta)\n', (24491, 24498), True, 'import numpy as np\n'), ((24554, 24571), 'numpy.radians', 'np.radians', (['theta'], {}), '(theta)\n', (24564, 24571), True, 'import numpy as np\n'), ((36529, 36562), 'statistics.mean', 'stc.mean', (["self.variaveisLog['tt']"], {}), "(self.variaveisLog['tt'])\n", (36537, 36562), True, 'import statistics as stc\n'), ((36624, 36661), 'statistics.variance', 'stc.variance', (["self.variaveisLog['tt']"], {}), "(self.variaveisLog['tt'])\n", (36636, 36661), True, 'import statistics as stc\n'), ((36727, 36761), 'statistics.stdev', 'stc.stdev', (["self.variaveisLog['tt']"], {}), "(self.variaveisLog['tt'])\n", (36736, 36761), True, 'import statistics as stc\n'), ((38345, 38378), 'statistics.mean', 'stc.mean', (["self.variaveisLog['tt']"], {}), "(self.variaveisLog['tt'])\n", (38353, 38378), True, 'import statistics as stc\n'), ((4893, 4907), 'datetime.datetime.now', 'datetime.now', ([], {}), '()\n', (4905, 4907), False, 'from datetime import datetime\n'), ((38480, 38517), 'statistics.variance', 'stc.variance', (["self.variaveisLog['tt']"], {}), "(self.variaveisLog['tt'])\n", (38492, 38517), True, 'import statistics as stc\n'), ((38594, 38628), 'statistics.stdev', 'stc.stdev', (["self.variaveisLog['tt']"], {}), "(self.variaveisLog['tt'])\n", (38603, 38628), True, 'import statistics as stc\n')]
import numpy as np from deepscratch.models.layers.activations.activation import Activation class Relu(Activation): # https://github.com/eriklindernoren/ML-From-Scratch/blob/master/mlfromscratch/deep_learning/activation_functions.py def __call__(self, data): return np.where(data >= 0, data, 0) def grads(self, data): return np.where(data >= 0, 1, 0) class LeakyRelu(): # https://github.com/eriklindernoren/ML-From-Scratch/blob/master/mlfromscratch/deep_learning/activation_functions.py def __init__(self, alpha=0.2): self.alpha = alpha def __call__(self, data): return np.where(data >= 0, data, self.alpha * data) def grads(self, data): return np.where(data >= 0, 1, self.alpha) class Elu(): # https://github.com/eriklindernoren/ML-From-Scratch/blob/master/mlfromscratch/deep_learning/activation_functions.py def __init__(self, alpha=0.2): self.alpha = alpha def __call__(self, data): return np.where(data >= 0.0, data, self.alpha * (np.exp(data) - 1)) def grads(self, data): return np.where(data >= 0.0, 1, self.__call__(data) + self.alpha) class Selu(): # https://github.com/eriklindernoren/ML-From-Scratch/blob/master/mlfromscratch/deep_learning/activation_functions.py # https://arxiv.org/abs/1706.02515, # https://github.com/bioinf-jku/SNNs/blob/master/SelfNormalizingNetworks_MLP_MNIST.ipynb def __init__(self): self.alpha = 1.6732632423543772848170429916717 self.scale = 1.0507009873554804934193349852946 def __call__(self, data): return self.scale * np.where(data >= 0.0, data, self.alpha*(np.exp(data)-1)) def grads(self, data): return self.scale * np.where(data >= 0.0, 1, self.alpha * np.exp(data))
[ "numpy.where", "numpy.exp" ]
[((283, 311), 'numpy.where', 'np.where', (['(data >= 0)', 'data', '(0)'], {}), '(data >= 0, data, 0)\n', (291, 311), True, 'import numpy as np\n'), ((359, 384), 'numpy.where', 'np.where', (['(data >= 0)', '(1)', '(0)'], {}), '(data >= 0, 1, 0)\n', (367, 384), True, 'import numpy as np\n'), ((635, 679), 'numpy.where', 'np.where', (['(data >= 0)', 'data', '(self.alpha * data)'], {}), '(data >= 0, data, self.alpha * data)\n', (643, 679), True, 'import numpy as np\n'), ((723, 757), 'numpy.where', 'np.where', (['(data >= 0)', '(1)', 'self.alpha'], {}), '(data >= 0, 1, self.alpha)\n', (731, 757), True, 'import numpy as np\n'), ((1045, 1057), 'numpy.exp', 'np.exp', (['data'], {}), '(data)\n', (1051, 1057), True, 'import numpy as np\n'), ((1781, 1793), 'numpy.exp', 'np.exp', (['data'], {}), '(data)\n', (1787, 1793), True, 'import numpy as np\n'), ((1670, 1682), 'numpy.exp', 'np.exp', (['data'], {}), '(data)\n', (1676, 1682), True, 'import numpy as np\n')]
from __future__ import division, print_function, absolute_import import numpy as np import matplotlib.pyplot as plt import streamlit as st import pandas as pd import seaborn as sns import random from sklearn.model_selection import RepeatedKFold, train_test_split, cross_val_score, StratifiedKFold, RepeatedStratifiedKFold, GridSearchCV from sklearn import svm, preprocessing from models import PCA, autoencoder, model_prep from sklearn.preprocessing import StandardScaler, MinMaxScaler from models.model_prep import Model from utils import reporter from sklearn.pipeline import make_pipeline from sklearn.metrics import precision_recall_curve, roc_curve, auc, f1_score def svmachine(method, df_data, df_demog, regress, tracts, group, hemi, metric, reps): #1 Select features X = model_prep.select_features(method, df_data, tracts, hemi) dis = df_demog.apply(lambda x: True if x['Group'] == group else False , axis=1) hcs = df_demog.apply(lambda x: True if x['Group'] == 0 else False , axis=1) # Count number of True in series and find ratio of HC/PAT for splitting numOfdis = len(dis[dis == True].index) numOfhcs = len(hcs[hcs == True].index) ratio = numOfdis/(numOfhcs+numOfdis) st.write("Ratio subjects/controls:", np.round(ratio,2)) X = X[(X['Group'] == 0) | (X['Group'] == group)] y = X[['Group']] X = X.drop(['Group', 'ID'], axis=1) #scaler = MinMaxScaler(feature_range=(0, 1)) #X[X.columns] = scaler.fit_transform(X[X.columns]) param_grid = [{'kernel': ['rbf'], 'gamma': [0.001, 0.01, 0.1, 1, 10, 100, 1000], 'C': [1, 10, 100, 1000]}, {'kernel': ['linear'], 'C': [1, 10, 100, 1000]}] grid_search = GridSearchCV(svm.SVC(class_weight={0:ratio, group:1-ratio}), param_grid, scoring = "roc_auc") scores = [] #best_svc = svm.SVC(kernel='linear', C=1, class_weight={0:ratio, group:1-ratio}) cv = RepeatedStratifiedKFold(n_splits=5, n_repeats=reps, random_state=42) for train_index, test_index in cv.split(X,y): X_train, X_test, y_train, y_test = X.iloc[train_index], X.iloc[test_index], y.iloc[train_index], y.iloc[test_index] if(regress): if'sex' in df_demog and 'age' in df_demog: X_train, X_test = model_prep.regress_confound(X_train, X_test, df_demog) else: st.error("No age or sex information found. Skipping regression step.") scaler, X_train, X_test = model_prep.normalize_features(X_train, X_test,method) #best_svc.fit(X_train, y_train.values.ravel()) grid_search.fit(X_train, y_train.values.ravel()) y_pred = grid_search.predict(X_test) fpr, tpr, thresholds = roc_curve(y_test, y_pred,group) auc_score = auc(fpr, tpr) #st.write(auc_score) scores.append(auc_score) st.success("Mean AUC: %0.2f (+/- %0.2f)" % (np.round(np.mean(scores), 2), np.round(np.std(scores),2))) return scores def run(method, df_data, df_demog, regress, tracts, group, hemi, metric, reps): st.warning("Computing permutations ... estimated time: " + str(np.round(len(df_demog)*2/60,2)) + " minutes.") if 'sex' not in df_demog and 'age' not in df_demog: st.error("No age or sex information found. Skipping regression step.") #1 Select features X = model_prep.select_features(method, df_data, tracts, hemi) # Get a bool series representing which row satisfies the condition i.e. True for # row in which value of group == 0 #st.write(X) dis = df_demog.apply(lambda x: True if x['Group'] == group else False , axis=1) hcs = df_demog.apply(lambda x: True if x['Group'] == 0 else False , axis=1) # Count number of True in series and find ratio of HC/PAT for splitting numOfdis = len(dis[dis == True].index) numOfhcs = len(hcs[hcs == True].index) ratio = numOfdis/numOfhcs #To accumulate error Distances DISTS = np.zeros(len(X)) countInserts = np.zeros(len(X)) count=0 #Separate HC from PATIENTS HC = X[X['Group'] == 0] y_HC = HC[['Group', 'ID']] PATIENTS = X[X['Group'] == group] y_PAT = PATIENTS[['Group', 'ID']] ##2 HERE, basically split the data into train and Val (split_size*repeats times) into equal size of HC/PAT. #split_size = int(np.ceil((float(numOfhcs)/numOfdis))) split_size = 5 #st.write (split_size, numOfhcs, numOfdis) repeats = reps #random_state = 12883823 #random_state=42 #rkf = RepeatedKFold(n_splits=split_size, n_repeats=repeats, random_state=random_state) AUC = np.zeros(repeats) tpr = [] fpr = [] #for train_idx, test_idx in rkf.split(HC,y_HC): for r in range(repeats): st.write("Iteration", r+1 , "of", repeats) X_train_split, X_test_split, y_train_split, y_test_split = train_test_split(HC, y_HC, test_size=min(0.2,ratio)) #X_train_split, X_test_split = HC.iloc[train_idx], HC.iloc[test_idx] #y_train_split, y_test_split = y_HC.iloc[train_idx], y_HC.iloc[test_idx] #Select subset of patients patients_subset_ids = np.array(random.sample(list(PATIENTS.index), min(len(X_test_split), len(PATIENTS)))) #Cating the HC test with the PATIENTS X_test_split = pd.concat([X_test_split,PATIENTS.loc[patients_subset_ids]]) y_test_split = pd.concat([y_test_split, y_PAT.loc[patients_subset_ids]]) X_train_split = X_train_split.drop(['Group', 'ID'], axis=1) X_test_split = X_test_split.drop(['Group', 'ID'], axis=1) #3 Linear regression of confound if(regress): if'sex' in df_demog and 'age' in df_demog: X_train_split, X_test_split = model_prep.regress_confound(X_train_split, X_test_split, df_demog) #4 Normalize features if method != "Z-score": scaler, X_train, X_test = model_prep.normalize_features(X_train_split, X_test_split, method) else: X_train, X_test = X_train_split, X_test_split #5 Anomaly detection method if method == "Z-score": model = Model(X_train, X_test, "Z-score") elif method == "PCA": model = Model(X_train, X_test, "PCA") else: model = Model(X_train, X_test, "Autoencoder") #6 Run d_train, d_test = model.run() DISTS[d_test.index] = DISTS[d_test.index] + d_test.values countInserts[d_test.index] += 1 #7 Evaluate result = model_prep.evaluate(d_train, d_test, y_HC, y_PAT, method) AUC[count], f, t = reporter.report_steps("ROC", result, method, group, metric, False) tpr.append(t) fpr.append(f) count = count + 1 #Assemble results / Aggregate and plot mean/median distributions DISTS /= countInserts WW = pd.DataFrame() WW['ID'] = X['ID'] WW['Group'] = X['Group'] WW['Dist'] = DISTS return AUC, WW, fpr, tpr
[ "pandas.DataFrame", "utils.reporter.report_steps", "streamlit.error", "sklearn.metrics.roc_curve", "models.model_prep.select_features", "models.model_prep.normalize_features", "numpy.std", "sklearn.model_selection.RepeatedStratifiedKFold", "numpy.zeros", "models.model_prep.Model", "streamlit.wri...
[((790, 847), 'models.model_prep.select_features', 'model_prep.select_features', (['method', 'df_data', 'tracts', 'hemi'], {}), '(method, df_data, tracts, hemi)\n', (816, 847), False, 'from models import PCA, autoencoder, model_prep\n'), ((1979, 2047), 'sklearn.model_selection.RepeatedStratifiedKFold', 'RepeatedStratifiedKFold', ([], {'n_splits': '(5)', 'n_repeats': 'reps', 'random_state': '(42)'}), '(n_splits=5, n_repeats=reps, random_state=42)\n', (2002, 2047), False, 'from sklearn.model_selection import RepeatedKFold, train_test_split, cross_val_score, StratifiedKFold, RepeatedStratifiedKFold, GridSearchCV\n'), ((3466, 3523), 'models.model_prep.select_features', 'model_prep.select_features', (['method', 'df_data', 'tracts', 'hemi'], {}), '(method, df_data, tracts, hemi)\n', (3492, 3523), False, 'from models import PCA, autoencoder, model_prep\n'), ((4728, 4745), 'numpy.zeros', 'np.zeros', (['repeats'], {}), '(repeats)\n', (4736, 4745), True, 'import numpy as np\n'), ((7052, 7066), 'pandas.DataFrame', 'pd.DataFrame', ([], {}), '()\n', (7064, 7066), True, 'import pandas as pd\n'), ((1262, 1280), 'numpy.round', 'np.round', (['ratio', '(2)'], {}), '(ratio, 2)\n', (1270, 1280), True, 'import numpy as np\n'), ((1783, 1835), 'sklearn.svm.SVC', 'svm.SVC', ([], {'class_weight': '{(0): ratio, group: 1 - ratio}'}), '(class_weight={(0): ratio, group: 1 - ratio})\n', (1790, 1835), False, 'from sklearn import svm, preprocessing\n'), ((2595, 2649), 'models.model_prep.normalize_features', 'model_prep.normalize_features', (['X_train', 'X_test', 'method'], {}), '(X_train, X_test, method)\n', (2624, 2649), False, 'from models import PCA, autoencoder, model_prep\n'), ((2837, 2869), 'sklearn.metrics.roc_curve', 'roc_curve', (['y_test', 'y_pred', 'group'], {}), '(y_test, y_pred, group)\n', (2846, 2869), False, 'from sklearn.metrics import precision_recall_curve, roc_curve, auc, f1_score\n'), ((2889, 2902), 'sklearn.metrics.auc', 'auc', (['fpr', 'tpr'], {}), '(fpr, tpr)\n', (2892, 2902), False, 'from sklearn.metrics import precision_recall_curve, roc_curve, auc, f1_score\n'), ((3359, 3429), 'streamlit.error', 'st.error', (['"""No age or sex information found. Skipping regression step."""'], {}), "('No age or sex information found. Skipping regression step.')\n", (3367, 3429), True, 'import streamlit as st\n'), ((4861, 4904), 'streamlit.write', 'st.write', (['"""Iteration"""', '(r + 1)', '"""of"""', 'repeats'], {}), "('Iteration', r + 1, 'of', repeats)\n", (4869, 4904), True, 'import streamlit as st\n'), ((5402, 5462), 'pandas.concat', 'pd.concat', (['[X_test_split, PATIENTS.loc[patients_subset_ids]]'], {}), '([X_test_split, PATIENTS.loc[patients_subset_ids]])\n', (5411, 5462), True, 'import pandas as pd\n'), ((5485, 5542), 'pandas.concat', 'pd.concat', (['[y_test_split, y_PAT.loc[patients_subset_ids]]'], {}), '([y_test_split, y_PAT.loc[patients_subset_ids]])\n', (5494, 5542), True, 'import pandas as pd\n'), ((6720, 6777), 'models.model_prep.evaluate', 'model_prep.evaluate', (['d_train', 'd_test', 'y_HC', 'y_PAT', 'method'], {}), '(d_train, d_test, y_HC, y_PAT, method)\n', (6739, 6777), False, 'from models import PCA, autoencoder, model_prep\n'), ((6805, 6871), 'utils.reporter.report_steps', 'reporter.report_steps', (['"""ROC"""', 'result', 'method', 'group', 'metric', '(False)'], {}), "('ROC', result, method, group, metric, False)\n", (6826, 6871), False, 'from utils import reporter\n'), ((6094, 6160), 'models.model_prep.normalize_features', 'model_prep.normalize_features', (['X_train_split', 'X_test_split', 'method'], {}), '(X_train_split, X_test_split, method)\n', (6123, 6160), False, 'from models import PCA, autoencoder, model_prep\n'), ((6326, 6359), 'models.model_prep.Model', 'Model', (['X_train', 'X_test', '"""Z-score"""'], {}), "(X_train, X_test, 'Z-score')\n", (6331, 6359), False, 'from models.model_prep import Model\n'), ((2332, 2386), 'models.model_prep.regress_confound', 'model_prep.regress_confound', (['X_train', 'X_test', 'df_demog'], {}), '(X_train, X_test, df_demog)\n', (2359, 2386), False, 'from models import PCA, autoencoder, model_prep\n'), ((2477, 2547), 'streamlit.error', 'st.error', (['"""No age or sex information found. Skipping regression step."""'], {}), "('No age or sex information found. Skipping regression step.')\n", (2485, 2547), True, 'import streamlit as st\n'), ((5858, 5924), 'models.model_prep.regress_confound', 'model_prep.regress_confound', (['X_train_split', 'X_test_split', 'df_demog'], {}), '(X_train_split, X_test_split, df_demog)\n', (5885, 5924), False, 'from models import PCA, autoencoder, model_prep\n'), ((6410, 6439), 'models.model_prep.Model', 'Model', (['X_train', 'X_test', '"""PCA"""'], {}), "(X_train, X_test, 'PCA')\n", (6415, 6439), False, 'from models.model_prep import Model\n'), ((6474, 6511), 'models.model_prep.Model', 'Model', (['X_train', 'X_test', '"""Autoencoder"""'], {}), "(X_train, X_test, 'Autoencoder')\n", (6479, 6511), False, 'from models.model_prep import Model\n'), ((3027, 3042), 'numpy.mean', 'np.mean', (['scores'], {}), '(scores)\n', (3034, 3042), True, 'import numpy as np\n'), ((3057, 3071), 'numpy.std', 'np.std', (['scores'], {}), '(scores)\n', (3063, 3071), True, 'import numpy as np\n')]
import numpy as np # Shared AGE_RANGES = np.arange(0, 100, 5) # For scalars TREE_SCALARS = { "Arterial": { "All": ["Scalars"], "BloodPressure": ["Scalars"], "Carotids": ["Scalars"], "PWA": ["Scalars"], }, "Biochemistry": {"All": ["Scalars"], "Blood": ["Scalars"], "Urine": ["Scalars"]}, "BloodCells": {"BloodCount": ["Scalars"]}, "Brain": { "All": ["Scalars"], "Cognitive": [ "AllScalars", "ReactionTime", "MatrixPatternCompletion", "TowerRearranging", "SymbolDigitSubstitution", "PairedAssociativeLearning", "ProspectiveMemory", "NumericMemory", "FluidIntelligence", "TrailMaking", "PairsMatching", ], "MRI": ["AllScalars", "dMRIWeightedMeans", "GreyMatterVolumes", "SubcorticalVolumes"], }, "Demographics": {"All": ["Scalars"]}, "Eyes": { "Acuity": ["Scalars"], "All": ["Scalars"], "Autorefraction": ["Scalars"], "IntraocularPressure": ["Scalars"], }, "Hearing": {"HearingTest": ["Scalars"]}, "Heart": {"All": ["Scalars"], "ECG": ["Scalars"], "MRI": ["Size", "PWA", "AllScalars"]}, "Lungs": {"Spirometry": ["Scalars"]}, "Musculoskeletal": { "Scalars": ["AllScalars", "Anthropometry", "Impedance", "HeelBoneDensitometry", "HandGripStrength"] }, "PhysicalActivity": {"FullWeek": ["Scalars"]}, } ETHNICITIES = [ "Do_not_know", "Prefer_not_to_answer", "NA", "White", "British", "Irish", "White_Other", "Mixed", "White_and_Black_Caribbean", "White_and_Black_African", "White_and_Asian", "Mixed_Other", "Asian", "Indian", "Pakistani", "Bangladeshi", "Asian_Other", "Black", "Caribbean", "African", "Black_Other", "Chinese", "Other_ethnicity", "Other", ] SEX_VALUE = {"female": 0, "male": 1} SEX_COLOR = {"female": "Pink", "male": "Blue"} # For time series TREE_TIME_SERIES = { "Arterial": {"PulseWaveAnalysis": ["TimeSeries"]}, "Heart": {"ECG": ["TimeSeries"]}, "PhysicalActivity": {"FullWeek": ["Acceleration", "TimeSeriesFeatures"], "Walking": ["3D"]}, } INFORMATION_TIME_SERIES = { "Arterial": { "PulseWaveAnalysis": { "TimeSeries": { "nb_channel": 1, "y_label": "blood pressure [normalized]", "x_label": "Time (10 min / unit)", } } }, "Heart": { "ECG": { "TimeSeries": { "nb_channel": 15, "y_label": "5 uV / Lsb", "x_label": "Time (2 min / unit)", } } }, "PhysicalActivity": { "FullWeek": { "Acceleration": { "nb_channel": 1, "y_label": "miligravity", "x_label": "Time (1 min / unit)", }, "TimeSeriesFeatures": { "nb_channel": 113, "y_label": "Acceleration", "x_label": "Time (5 min / unit)", }, }, "Walking": { "3D": { "nb_channel": 3, "y_label": "Acceleration", "x_label": "Time (2 min / unit)", } }, }, } # For images TREE_IMAGES = { "Abdomen": {"Liver": ["Raw", "Contrast"], "Pancreas": ["Raw", "Contrast"]}, "Arterial": {"Carotids": ["CIMT120", "CIMT150", "LongAxis", "Mixed", "ShortAxis"]}, "Brain": { "MRI": [ "SagittalRaw", "SagittalReference", "CoronalRaw", "CoronalReference", "TransverseRaw", "TransverseReference", ] }, "Eyes": {"Fundus": ["Raw"], "OCT": ["Raw"]}, "Heart": { "MRI": [ "2chambersRaw", "2chambersContrast", "3chambersRaw", "3chambersContrast", "4chambersRaw", "4chambersContrast", ] }, "Musculoskeletal": { "FullBody": ["Figure", "Flesh", "Mixed", "Skeleton"], "Knees": ["DXA"], "Hips": ["DXA"], "Spine": ["Coronal", "Sagittal"], }, "PhysicalActivity": { "FullWeek": [ "GramianAngularField1minDifference", "GramianAngularField1minSummation", "MarkovTransitionField1min", "RecurrencePlots1min", ] }, } SIDES_DIMENSION = ["Arterial", "Eyes", "Musculoskeletal"] SIDES_SUBDIMENSION_EXCEPTION = ["FullBody", "Spine"] # For videos CHAMBERS_LEGEND = {"3": "3 chamber", "4": "4 chamber"} SEX_LEGEND = {"male": "Male", "female": "Female"} AGE_GROUP_LEGEND = {"young": "Young", "middle": "Middle", "old": "Old"} SAMPLE_LEGEND = {"0": 0, "1": 1, "2": 2, "3": 3, "4": 4, "5": 5, "6": 6, "7": 7, "8": 8, "9": 9}
[ "numpy.arange" ]
[((42, 62), 'numpy.arange', 'np.arange', (['(0)', '(100)', '(5)'], {}), '(0, 100, 5)\n', (51, 62), True, 'import numpy as np\n')]
''' invsolve/project.py ''' import dolfin import logging import numpy as np import scipy.linalg as linalg from scipy.spatial import cKDTree try: import wlsqm # optimized meshless except: # logging.log(logging.WARNING, repr(ModuleNotFoundError)) HAS_WLSQM = False else: HAS_WLSQM = True MESHLESS_NEIGHBORS_FROM_DEGREE = { 0 : round(5*5 * np.pi/4), 1 : round(7*7 * np.pi/4), 2 : round(9*9 * np.pi/4), } # Concervative estimate of the required number of nearest neighbors # in a circular 2D domain for projecting a (rather) noisy pointcloud. def project_pointvalues_on_functions(xk, fk, V_project, meshless_degree=0, num_neighbors=None, distance_norm=2, subdims_geo=None, subdims_val=None): '''Project measurements on functions using meshless interpolation. Given an array of points and a list of arrays of data values at those points, project these discrete values onto the degrees of freedom of a (vector-valued) function constructed from the function space by using the moving least squares meshless interpolation method. Parameters ---------- xk : numpy.ndarray Points where data values are known. fk : list of numpy.ndarray's A sequence of data values at the points `xk`. V_project : dolfin.FunctionSpace Vector-valued function space onto which to do meshless projection. The projection will be onto the degrees of freedom the function. meshless_degree : integer, optional (default=2) Degree of the meshless interpolation. num_neighbors : integer, optional Number of nearest neighbors to use in meshless interpolation. If `None` An appropriate number is chosen from experience. distance_norm : integer, optional (default=2) The distance norm to use in finding nearest neighbors. The common choices are: 2 (Euclidean distance), and 1 (Manhattan distance). subdims_geo : list of integers Indices into the dof-coordinate dimensions of `V_project`. The indexed dof coordinates will be used as the interpolation points `xi` where `fk`, which is only defined at `xk`, will be interpolated. subdims_val : list of integers Indices into the dof value dimensions of `V_project`. The indexed dof values of `V_project` will be the values obtained by interpolating `fk` at `xi`. Returns ------- fn : list of dolfin.Function's A list of functions. The functions correspond to the snapshots `fk` interplated at the degrees-of-freedom coordinates of the function space `V_project`. ''' if not isinstance(xk, np.ndarray) or not (1 <= xk.ndim <= 2): raise TypeError('Parameter `xk` must be a 1D or 2D `numpy.ndarray`.') if not isinstance(V_project, dolfin.FunctionSpace): raise TypeError('Parameter `V_project` must be a `dolfin.FunctionSpace`.') if isinstance(fk, np.ndarray): fk = (fk,) # must be a sequence else: if not isinstance(fk, (list,tuple)) or \ not all(isinstance(uk_i, np.ndarray) for uk_i in fk): raise TypeError('Parameter `fk` must be a `numpy.ndarray`, ' 'or a `list` or `tuple` of `numpy.ndarray`s.') if any(uk_i.shape != fk[0].shape for uk_i in fk[1:]): raise TypeError('Parameter `fk` must contain ' '`numpy.ndarray`s of the same shape.') if not (1 <= fk[0].ndim <= 2): raise TypeError('Parameter `fk` must contain ' 'either 1D or 2D `numpy.ndarray`s.') V = V_project # alias gdim_data = xk.size//len(xk) vdim_data = fk[0].size//len(fk[0]) gdim_proj = V.element().geometric_dimension() vdim_proj = V.element().num_sub_elements() if vdim_proj == 0: # scalar function space vdim_proj = 1 # supposed value dimension if gdim_data != gdim_proj: if not subdims_geo or gdim_data != len(subdims_geo): raise ValueError('Expected the same geometric dimension of parameter ' '`xk` (={gdim_data:d}) and parameter `V` (={gdim_proj:d}).') if vdim_data != vdim_proj: if not subdims_val or vdim_data != len(subdims_val): raise ValueError('Expected the same value dimension of parameter ' '`fk` (={vdim_data:d}) and parameter `V` (={vdim_proj:d}).') if vdim_proj > 1: # `V` is vector-valued (can be split) dofmap = [V_i.dofmap().dofs() for V_i in V.split()] else: # `V` is a scalar-valued (can not be split) dofmap = [V.dofmap().dofs()] dofcrd = V.tabulate_dof_coordinates().reshape((-1,gdim_proj)) dofcrd = [dofcrd[dofmap_i,:] for dofmap_i in dofmap] if __debug__: if not all(np.allclose(dofcrd[0], dofcrd_i) for dofcrd_i in dofcrd[1:]): raise TypeError('DOF coordinates of sub-dimensions are not the same.') xi = dofcrd[0] if gdim_data != gdim_proj: xi = xi[:,subdims_geo] if vdim_data != vdim_proj: dofmap = [dofmap[i] for i in subdims_val] fi = project_pointvalues_on_points(xk, fk, xi, meshless_degree, num_neighbors, distance_norm) fn = [] for fi_t in fi: fn.append(dolfin.Function(V)) fn_t = fn[-1].vector().get_local() for dofmap_j, fi_tj in zip(dofmap, fi_t.T): fn_t[dofmap_j] = fi_tj fn[-1].vector()[:] = fn_t return fn # list of functions def project_pointvalues_on_points(xk, fk, xi, meshless_degree=0, num_neighbors=None, distance_norm=2): ''' Parameters ---------- xk : numpy.ndarray Points where data values are known. fk : list of numpy.ndarray's A sequence of data values at the points `xk`. xi : numpy.ndarray Points where the known point values are to be projected. meshless_degree : integer, optional (default=2) Degree of the meshless interpolation. num_neighbors : integer, optional Number of nearest neighbors to use in meshless interpolation. If `None` An appropriate number is chosen from experience. distance_norm : integer, optional (default=2) The distance norm to use in finding nearest neighbors. The common choices are: 2 (Euclidean distance), and 1 (Manhattan distance). Returns ------- ui : list of numpy.ndarray's The projected point values. ''' if not isinstance(xk, np.ndarray) or not (1 <= xk.ndim <= 2): raise TypeError('Parameter `xk` must be a 1D or 2D `numpy.ndarray`.') if not isinstance(xi, np.ndarray) or not (1 <= xk.ndim <= 2): raise TypeError('Parameter `xk` must be a 1D or 2D `numpy.ndarray`.') if isinstance(fk, np.ndarray): fk = (fk,) # must be a sequence else: if not isinstance(fk, (list,tuple)) or \ not all(isinstance(fk_i, np.ndarray) for fk_i in fk): raise TypeError('Parameter `fk` must be a `numpy.ndarray`, ' 'or a `list` or `tuple` of `numpy.ndarray`s.') if any(fk_i.shape != fk[0].shape for fk_i in fk[1:]): raise TypeError('Parameter `fk` must contain ' '`numpy.ndarray`s of the same shape.') if not (1 <= fk[0].ndim <= 2): raise TypeError('Parameter `fk` must contain ' 'either 1D or 2D `numpy.ndarray`s.') if HAS_WLSQM: meshless = MeshlessInterpolation(xk, copy=False) else: meshless = SimpleMeshlessInterpolation2d(xk, copy=False) if not num_neighbors: num_neighbors = MESHLESS_NEIGHBORS_FROM_DEGREE[meshless_degree] len_fk = len(fk) dim_fk = fk[0].ndim if dim_fk == 1: fk = np.stack(fk, axis=1) else: # fk[0].ndim == 2: fk = np.concatenate(fk, axis=1) meshless.set_reference_values(fk, copy=False) meshless.set_interpolation_points(xi, num_neighbors, distance_norm, copy=False) fi = meshless.interpolate(degree=meshless_degree) fi = np.split(fi, len_fk, axis=1) if dim_fk == 1 and fi[0].ndim == 2: fi = [f.squeeze() for f in fi] return fi class SimpleMeshlessInterpolation2d: '''Does not depend on third party libraries. Use as fallback. However, the computational speed is several times slower than "wlsqm". Note, the solutions will be a bit different due to different weight functions used.''' @staticmethod def _eval_weight_uniform(r): '''Uniform weight function.''' return np.ones_like(r) @staticmethod def _eval_weight_center(r): '''The weight function "WEIGHT_CENTER" used in `wlsqm`.''' return np.where(r < 1.0, 1e-4 + (1.0-1e-4) * (1.0-r)**2, 1e-4) @staticmethod def _eval_basis_p0(ones, x, y): '''Linear polynomial basis in two spatial dimensions.''' return np.stack([ones], axis=1) @staticmethod def _eval_basis_p1(ones, x, y): '''Linear polynomial basis in two spatial dimensions.''' return np.stack([ones, x, y], axis=1) # C-contiguous @staticmethod def _eval_basis_p2(ones, x, y): '''Quadratic polynomial basis in two spatial dimensions.''' return np.stack([ones, x, y, x*x, x*y, y*y], axis=1) # C-contiguous def __init__(self, xk, fk=None, copy=True): if not isinstance(xk, np.ndarray) or xk.ndim != 2 or xk.shape[1] != 2: raise TypeError('Expected parameter `xi` to be a 2D `numpy.ndarray`.') self._gdim = 2 # NOTE: 2D meshless interpolation self._xk = np.array(xk, float, order='C', copy=copy) self._kdtree_xk = cKDTree(self._xk, copy_data=False) self._xi = None self._fk = None self._vdim = None self._neighbors_xi = None self._neighbors_ri = None if fk is not None: self.set_reference_values(fk, copy) # -> self._fk, self._vdim def set_reference_values(self, fk, copy=True): ''' Parameters ---------- fk : array or a list of 1-D arrays: Function values at `xk`. If `fk` is a np.ndarray, it must be either 1-D or 2D. If `fk` is a list or tuple, the items must be 1-D arrays of equal length. copy : bool (optional) Whether to copy data `fk` or not. ''' exc = TypeError('Parameter `fk` must either be a sequence (`list` or ' '`tuple`) of 1-D `np.ndarray`s of equal length, or a single 1-D ' '`np.ndarray` or a single 2D `np.ndarray`.') if isinstance(fk, (list,tuple)): if all(len(fk_i) == len(fk[0]) and isinstance(fk_i, np.ndarray) and fk_i.ndim == 1 for fk_i in fk): if all(len(fk_i) == len(self._xk) for fk_i in fk): self._fk = np.asarray(np.stack(fk, axis=1), order='C') self._vdim = len(fk) return else: raise exc else: raise exc elif isinstance(fk, np.ndarray): if len(fk) == len(self._xk): if fk.ndim == 2: self._fk = np.array(fk, order='C', copy=copy) self._vdim = fk.shape[1] return elif fk.ndim == 1: self._fk = np.array(fk[:,None], copy=copy) self._vdim = 1 return else: raise exc else: raise exc else: raise exc def set_interpolation_points(self, xi, num_neighbors, distance_norm=2, copy=True): ''' Parameters ---------- xi : np.ndarray Interpolation points where a function is to be interpolated. num_neighbors : integer Number of nearest neighbors to find. distance_norm : integer, optional Order of the dinstance norm for finding the nearest neighbors. ''' if not isinstance(xi, np.ndarray) or xi.ndim != 2: raise TypeError('Expected parameter `xi` to be a 2D `numpy.ndarray`.') if xi.shape[1] != self._gdim: raise ValueError('Expected geometric dimension of ' 'parameter `xi` to be the same as that of `xk`.') self._xi = np.array(xi, float, order='C', copy=copy) self._neighbors_ri, self._neighbors_xi = \ self._kdtree_xk.query(self._xi, k=num_neighbors, p=distance_norm) def interpolate(self, fk=None, degree=1, weight='uniform'): '''Interpolate previously given function values `fk` at new points `xi`. Parameters ---------- fk : np.ndarray, list of np.ndarray's Discrete function values at `xk`. If `fk` is a np.ndarray, its shape must be either 1D or 2D. If `fk` is a list or tuple, the elements must be equal length 1D arrays. degree: integer (optional) The degree of meshless interpolation. weight: string (optional) The kind of weighting method to use. There are two options: "uniform" or "center". The former is better suited to interpolating data that arises from a smooth function. The latter is better suited to interpolating data that arises from not a smooth function. Returns ------ fi : np.ndarray Interpolated function values at interpolation points `xi`. ''' if self._xi is None: raise AttributeError('`xi` is not set yet.') if fk is not None: self.set_reference_values(fk, copy=False) elif self._fk is None: raise AttributeError('`fk` is not set yet.') if degree == 0: eval_basis = self._eval_basis_p0 elif degree == 1: eval_basis = self._eval_basis_p1 elif degree == 2: eval_basis = self._eval_basis_p2 else: raise ValueError('degree?') if weight == 'uniform' : eval_weight = self._eval_weight_uniform elif weight == 'center' : eval_weight = self._eval_weight_center else: raise ValueError('Parameter `weight`: "uniform" or "center" ?') fk = self._fk xk = self._xk xi = self._xi neighbors_xi = self._neighbors_xi neighbors_ri = self._neighbors_ri ki = neighbors_xi.size // len(neighbors_xi) # number of neighbors if ki == 1: # single neighbor edge case neighbors_xi = neighbors_xi[:,None] neighbors_ri = neighbors_ri[:,None] I = np.ones((ki,), float) fi = np.empty((len(xi), self._vdim), float, order='C') for i, x0 in enumerate(xi): q = neighbors_xi[i,:] r = neighbors_ri[i,:] x = xk[q,0] - x0[0] y = xk[q,1] - x0[1] B = eval_basis(I, x, y) W = eval_weight(r/r.max()) BTW = B.T*W A = BTW.dot(B) b = BTW.dot(fk[q,:]) try: fi[i,:] = linalg.solve(A, b, sym_pos=True) # 0th item gives interpolation values at x0 except linalg.LinAlgError as err: print('WARNING: Number of nearest neighbors is too small. ' 'Assuming the mean value of the neighbors as the solution.') fi[i,:] = W.dot(fk[q,:])/W.sum() return fi @property def gdim(self): return self._gdim @property def vdim(self): return self._vdim class MeshlessInterpolation: '''Depends on third party library Meshless projection at points `xi` from a scatter of points `xk` and (vector-valued) function values `fk`.''' def __new__(cls, *args, **kwargs): if not HAS_WLSQM: raise ModuleNotFoundError('Require package "wlsqm".') return super(cls, cls).__new__(cls) def __init__(self, xk, fk=None, copy=True): ''' Give data points: point coordinates `xk` and (vector-valued) function values `fk`, prepare instance for meshless projection. Parameters ---------- xk : np.ndarray Data points where values of a function are known. fk : np.ndarray, list of np.ndarray's Discrete function values at `xk`. If `fk` is a np.ndarray, its shape must be either 1D or 2D. If `fk` is a list or tuple, the elements must be equal length 1D arrays. ''' if not isinstance(xk, np.ndarray) or xk.ndim != 2 or xk.shape[1] != 2: raise TypeError('Expected parameter `xi` to be a 2D `numpy.ndarray`.') self._gdim = 2 # NOTE: 2D meshless interpolation self._xk = np.array(xk, np.float64, order='C', copy=copy) self._kdtree_xk = cKDTree(self._xk, copy_data=False) self._xi = None self._fk = None self._vdim = None self._neighbors_xi = None self._neighbors_ri = None if fk is not None: self.set_reference_values(fk, copy) # -> self._fk, self._vdim def set_reference_values(self, fk, copy=True): ''' Parameters ---------- fk : array or a list of 1-D arrays: Function values at `xk`. If `fk` is a np.ndarray, it must be either 1-D or 2D. If `fk` is a list or tuple, the items must be 1-D arrays of equal length. copy : bool (optional) Whether to copy data `fk` or not. ''' exc = TypeError('Parameter `fk` must either be a sequence (`list` or ' '`tuple`) of 1-D `np.ndarray`s of equal length, or a single 1-D ' '`np.ndarray` or a single 2D `np.ndarray`.') if isinstance(fk, (list,tuple)): if all(len(fk_i) == len(fk[0]) and isinstance(fk_i, np.ndarray) and fk_i.ndim == 1 for fk_i in fk): if all(len(fk_i) == len(self._xk) for fk_i in fk): self._fk = [np.array(fk_i, np.float64, order='C', copy=copy) for fk_i in fk] self._vdim = len(self._fk) return else: raise exc else: raise exc elif isinstance(fk, np.ndarray): if len(fk) == len(self._xk): if fk.ndim == 2: self._fk = [np.array(fk_j, np.float64, order='C', copy=copy) for fk_j in fk.T] self._vdim = len(self._fk) return elif fk.ndim == 1: self._fk = [np.array(fk, np.float64, copy=copy)] self._vdim = 1 return else: raise exc else: raise exc else: raise exc def set_interpolation_points(self, xi, num_neighbors, distance_norm=2, copy=True): ''' Parameters ---------- xi : np.ndarray Interpolation points where a function is to be interpolated. num_neighbors : integer Number of nearest neighbors to find. distance_norm : integer, optional Order of the dinstance norm for finding the nearest neighbors. ''' if not isinstance(xi, np.ndarray) or xi.ndim != 2: raise TypeError('Expected parameter `xi` to be a 2D `np.ndarray`') if xi.shape[1] != self._gdim: raise ValueError('Expected geometric dimension of ' 'parameter `xi` to be the same as that of `xk`.') self._xi = np.array(xi, np.float64, order='C', copy=copy) self._neighbors_ri, self._neighbors_xi = \ self._kdtree_xk.query(self._xi, k=num_neighbors, p=distance_norm) def interpolate(self, fk=None, degree=1, weight='uniform'): '''Interpolate previously given function values `fk` at new points `xi`. Parameters ---------- fk : np.ndarray, list of np.ndarray's Discrete function values at `xk`. If `fk` is a np.ndarray, its shape must be either 1D or 2D. If `fk` is a list or tuple, the elements must be equal length 1D arrays. degree: integer (optional) The degree of meshless interpolation. weight: string (optional) The kind of weighting method to use. There are two options: "uniform" or "center". The former is better suited to interpolating data that arises from a smooth function. The latter is better suited to interpolating data that arises from not a smooth function. Returns ------ fi : np.ndarray Interpolated function values at interpolation points `xi`. ''' if self._xi is None: raise AttributeError('`xi` is not set yet.') if fk is not None: self.set_reference_values(fk, copy=False) elif self._fk is None: raise AttributeError('`fk` is not set yet.') if weight == 'uniform' : weight_method = wlsqm.WEIGHT_UNIFORM elif weight == 'center' : weight_method = wlsqm.WEIGHT_CENTER else: raise ValueError('Parameter `weight`: "uniform" or "center" ?') fk = self._fk xk = self._xk xi = self._xi ni = len(xi) neighbors_xi = self._neighbors_xi neighbors_ri = self._neighbors_ri ki = neighbors_xi.size // len(neighbors_xi) # number of neighbors if ki == 1: # single neighbor edge case neighbors_xi = neighbors_xi[:,None] neighbors_ri = neighbors_ri[:,None] fi = np.empty((ni, self._vdim), order='F', dtype=float) solution = np.zeros( shape=(ni, wlsqm.number_of_dofs(self._gdim, degree)), dtype=np.float64) # worker array knowns = np.zeros( shape=(ni,), dtype=np.int64) # nothing's known about `fi` neighbors = np.full( shape=(ni,), fill_value=ki, dtype=np.int32) order = np.full( shape=(ni,), fill_value=degree, dtype=np.int32) weighting_method = np.full( shape=(ni,), fill_value=weight_method, dtype=np.int32) for i, fk_i in enumerate(fk): wlsqm.fit_2D_many_parallel(xk[neighbors_xi], fk_i[neighbors_xi], nk=neighbors, xi=xi, fi=solution, sens=None, do_sens=False, order=order, knowns=knowns, weighting_method=weighting_method) fi[:,i] = solution[:,0] # interpolated values are in 0th column q_nan = np.isnan(fi[:,i]) if np.any(q_nan): print('WARNING: Number of nearest neighbors is too small. ' 'Assuming the mean value of the neighbors as the solution.') fi[q_nan,i] = fk_i[neighbors_xi[q_nan,:]].mean(axis=1) return fi @property def gdim(self): return self._gdim @property def vdim(self): return self._vdim
[ "numpy.stack", "numpy.full", "scipy.linalg.solve", "numpy.ones_like", "numpy.empty", "numpy.allclose", "numpy.zeros", "numpy.ones", "dolfin.Function", "numpy.split", "numpy.isnan", "wlsqm.fit_2D_many_parallel", "numpy.any", "numpy.where", "numpy.array", "scipy.spatial.cKDTree", "wlsq...
[((7952, 7980), 'numpy.split', 'np.split', (['fi', 'len_fk'], {'axis': '(1)'}), '(fi, len_fk, axis=1)\n', (7960, 7980), True, 'import numpy as np\n'), ((7653, 7673), 'numpy.stack', 'np.stack', (['fk'], {'axis': '(1)'}), '(fk, axis=1)\n', (7661, 7673), True, 'import numpy as np\n'), ((7716, 7742), 'numpy.concatenate', 'np.concatenate', (['fk'], {'axis': '(1)'}), '(fk, axis=1)\n', (7730, 7742), True, 'import numpy as np\n'), ((8452, 8467), 'numpy.ones_like', 'np.ones_like', (['r'], {}), '(r)\n', (8464, 8467), True, 'import numpy as np\n'), ((8601, 8668), 'numpy.where', 'np.where', (['(r < 1.0)', '(0.0001 + (1.0 - 0.0001) * (1.0 - r) ** 2)', '(0.0001)'], {}), '(r < 1.0, 0.0001 + (1.0 - 0.0001) * (1.0 - r) ** 2, 0.0001)\n', (8609, 8668), True, 'import numpy as np\n'), ((8792, 8816), 'numpy.stack', 'np.stack', (['[ones]'], {'axis': '(1)'}), '([ones], axis=1)\n', (8800, 8816), True, 'import numpy as np\n'), ((8952, 8982), 'numpy.stack', 'np.stack', (['[ones, x, y]'], {'axis': '(1)'}), '([ones, x, y], axis=1)\n', (8960, 8982), True, 'import numpy as np\n'), ((9136, 9187), 'numpy.stack', 'np.stack', (['[ones, x, y, x * x, x * y, y * y]'], {'axis': '(1)'}), '([ones, x, y, x * x, x * y, y * y], axis=1)\n', (9144, 9187), True, 'import numpy as np\n'), ((9487, 9528), 'numpy.array', 'np.array', (['xk', 'float'], {'order': '"""C"""', 'copy': 'copy'}), "(xk, float, order='C', copy=copy)\n", (9495, 9528), True, 'import numpy as np\n'), ((9555, 9589), 'scipy.spatial.cKDTree', 'cKDTree', (['self._xk'], {'copy_data': '(False)'}), '(self._xk, copy_data=False)\n', (9562, 9589), False, 'from scipy.spatial import cKDTree\n'), ((12211, 12252), 'numpy.array', 'np.array', (['xi', 'float'], {'order': '"""C"""', 'copy': 'copy'}), "(xi, float, order='C', copy=copy)\n", (12219, 12252), True, 'import numpy as np\n'), ((14473, 14494), 'numpy.ones', 'np.ones', (['(ki,)', 'float'], {}), '((ki,), float)\n', (14480, 14494), True, 'import numpy as np\n'), ((16608, 16654), 'numpy.array', 'np.array', (['xk', 'np.float64'], {'order': '"""C"""', 'copy': 'copy'}), "(xk, np.float64, order='C', copy=copy)\n", (16616, 16654), True, 'import numpy as np\n'), ((16681, 16715), 'scipy.spatial.cKDTree', 'cKDTree', (['self._xk'], {'copy_data': '(False)'}), '(self._xk, copy_data=False)\n', (16688, 16715), False, 'from scipy.spatial import cKDTree\n'), ((19462, 19508), 'numpy.array', 'np.array', (['xi', 'np.float64'], {'order': '"""C"""', 'copy': 'copy'}), "(xi, np.float64, order='C', copy=copy)\n", (19470, 19508), True, 'import numpy as np\n'), ((21526, 21576), 'numpy.empty', 'np.empty', (['(ni, self._vdim)'], {'order': '"""F"""', 'dtype': 'float'}), "((ni, self._vdim), order='F', dtype=float)\n", (21534, 21576), True, 'import numpy as np\n'), ((21736, 21773), 'numpy.zeros', 'np.zeros', ([], {'shape': '(ni,)', 'dtype': 'np.int64'}), '(shape=(ni,), dtype=np.int64)\n', (21744, 21773), True, 'import numpy as np\n'), ((21849, 21900), 'numpy.full', 'np.full', ([], {'shape': '(ni,)', 'fill_value': 'ki', 'dtype': 'np.int32'}), '(shape=(ni,), fill_value=ki, dtype=np.int32)\n', (21856, 21900), True, 'import numpy as np\n'), ((21955, 22010), 'numpy.full', 'np.full', ([], {'shape': '(ni,)', 'fill_value': 'degree', 'dtype': 'np.int32'}), '(shape=(ni,), fill_value=degree, dtype=np.int32)\n', (21962, 22010), True, 'import numpy as np\n'), ((22076, 22138), 'numpy.full', 'np.full', ([], {'shape': '(ni,)', 'fill_value': 'weight_method', 'dtype': 'np.int32'}), '(shape=(ni,), fill_value=weight_method, dtype=np.int32)\n', (22083, 22138), True, 'import numpy as np\n'), ((5213, 5231), 'dolfin.Function', 'dolfin.Function', (['V'], {}), '(V)\n', (5228, 5231), False, 'import dolfin\n'), ((22228, 22424), 'wlsqm.fit_2D_many_parallel', 'wlsqm.fit_2D_many_parallel', (['xk[neighbors_xi]', 'fk_i[neighbors_xi]'], {'nk': 'neighbors', 'xi': 'xi', 'fi': 'solution', 'sens': 'None', 'do_sens': '(False)', 'order': 'order', 'knowns': 'knowns', 'weighting_method': 'weighting_method'}), '(xk[neighbors_xi], fk_i[neighbors_xi], nk=\n neighbors, xi=xi, fi=solution, sens=None, do_sens=False, order=order,\n knowns=knowns, weighting_method=weighting_method)\n', (22254, 22424), False, 'import wlsqm\n'), ((22545, 22563), 'numpy.isnan', 'np.isnan', (['fi[:, i]'], {}), '(fi[:, i])\n', (22553, 22563), True, 'import numpy as np\n'), ((22579, 22592), 'numpy.any', 'np.any', (['q_nan'], {}), '(q_nan)\n', (22585, 22592), True, 'import numpy as np\n'), ((14935, 14967), 'scipy.linalg.solve', 'linalg.solve', (['A', 'b'], {'sym_pos': '(True)'}), '(A, b, sym_pos=True)\n', (14947, 14967), True, 'import scipy.linalg as linalg\n'), ((4743, 4775), 'numpy.allclose', 'np.allclose', (['dofcrd[0]', 'dofcrd_i'], {}), '(dofcrd[0], dofcrd_i)\n', (4754, 4775), True, 'import numpy as np\n'), ((21630, 21670), 'wlsqm.number_of_dofs', 'wlsqm.number_of_dofs', (['self._gdim', 'degree'], {}), '(self._gdim, degree)\n', (21650, 21670), False, 'import wlsqm\n'), ((10769, 10789), 'numpy.stack', 'np.stack', (['fk'], {'axis': '(1)'}), '(fk, axis=1)\n', (10777, 10789), True, 'import numpy as np\n'), ((11080, 11114), 'numpy.array', 'np.array', (['fk'], {'order': '"""C"""', 'copy': 'copy'}), "(fk, order='C', copy=copy)\n", (11088, 11114), True, 'import numpy as np\n'), ((17897, 17945), 'numpy.array', 'np.array', (['fk_i', 'np.float64'], {'order': '"""C"""', 'copy': 'copy'}), "(fk_i, np.float64, order='C', copy=copy)\n", (17905, 17945), True, 'import numpy as np\n'), ((11254, 11286), 'numpy.array', 'np.array', (['fk[:, None]'], {'copy': 'copy'}), '(fk[:, None], copy=copy)\n', (11262, 11286), True, 'import numpy as np\n'), ((18271, 18319), 'numpy.array', 'np.array', (['fk_j', 'np.float64'], {'order': '"""C"""', 'copy': 'copy'}), "(fk_j, np.float64, order='C', copy=copy)\n", (18279, 18319), True, 'import numpy as np\n'), ((18504, 18539), 'numpy.array', 'np.array', (['fk', 'np.float64'], {'copy': 'copy'}), '(fk, np.float64, copy=copy)\n', (18512, 18539), True, 'import numpy as np\n')]
import numpy as np import scipy.stats import sklearn def iqr(value: np.ndarray): return np.percentile(value, 75) - np.percentile(value, 25) def cv(value_array: np.ndarray, min_quant_value_num=3, std_ddof=1, make_percentage=True, keep_na=False, decimal_place=None, return_iqr=False): """ :param value_array: A two-dimensional array with rows as sample and cols as replicates. CV will be performed to each row (dim 0) :param min_quant_value_num: Minimum number of non-NA values :param std_ddof: ddof for std :param make_percentage: If true, CVs will be multi with 100, else nothing will do. Default True :param keep_na: Whether to return NAs for those CV-unavailable samples. If True, the returned CVs will have the same size as input samples. Default False :param decimal_place: :param return_iqr: Whether to return IQR of calulated CVs. If True, a tuple like (cvs, iqr) will be returned, otherwise cvs only. Default False """ if len(value_array.shape) != 2: raise ValueError(f'Calc CV would expects a two-dim array with sample as rows and replicates as cols. Current input array has {len(value_array.shape)} dim') sample_num, rep_num = value_array.shape if min_quant_value_num > rep_num: min_quant_value_num = rep_num cv_avail_value_idx = np.where((rep_num - np.isnan(value_array).sum(axis=1)) >= min_quant_value_num)[0] cv_avail_values = value_array[cv_avail_value_idx] cvs = np.nanstd(cv_avail_values, axis=1, ddof=std_ddof) / np.nanmean(cv_avail_values, axis=1) if make_percentage: cvs = cvs * 100 if keep_na: temp = np.zeros(sample_num) temp.fill(np.nan) temp[cv_avail_value_idx] = cvs cvs = temp.copy() return cvs def count_missing_values(value_array: np.ndarray, keep_all_na_row=True): mvs = np.sum(np.isnan(value_array), axis=1) return mvs def fwhm(values: np.ndarray, est_x_num=1e3): """ :return: A tuple as (FWHM value, APEX point, Max estimated Y, KDE func) """ sorted_values = np.sort(values) kde = scipy.stats.kde.gaussian_kde(sorted_values) kde_x = np.linspace(sorted_values[0], sorted_values[-1], int(est_x_num)) kde_y = kde(kde_x) max_est_y = np.max(kde_y) apex_x_idx = np.argmax(kde_y) fwhm_min_idx = np.where(kde_y[:apex_x_idx] < kde_y[apex_x_idx] / 2)[0][-1] fwhm_max_idx = np.where(kde_y[apex_x_idx:] < kde_y[apex_x_idx] / 2)[0][0] + apex_x_idx apex_point = kde_x[apex_x_idx] fwhm_value = kde_x[fwhm_max_idx] - kde_x[fwhm_min_idx] return fwhm_value, apex_point, max_est_y, kde # def pca(): # cond_quant_df = quant_df[conditions].dropna(how='any').copy() # pca_input_values = cond_quant_df.values.T # pca = sklearn.decomposition.PCA(n_components=2).fit(pca_input_values) # component_var = pca.explained_variance_ratio_ # transformed_values = pca.transform(pca_input_values)
[ "numpy.argmax", "numpy.nanstd", "numpy.zeros", "numpy.isnan", "numpy.percentile", "numpy.sort", "numpy.max", "numpy.where", "numpy.nanmean" ]
[((2052, 2067), 'numpy.sort', 'np.sort', (['values'], {}), '(values)\n', (2059, 2067), True, 'import numpy as np\n'), ((2238, 2251), 'numpy.max', 'np.max', (['kde_y'], {}), '(kde_y)\n', (2244, 2251), True, 'import numpy as np\n'), ((2269, 2285), 'numpy.argmax', 'np.argmax', (['kde_y'], {}), '(kde_y)\n', (2278, 2285), True, 'import numpy as np\n'), ((94, 118), 'numpy.percentile', 'np.percentile', (['value', '(75)'], {}), '(value, 75)\n', (107, 118), True, 'import numpy as np\n'), ((121, 145), 'numpy.percentile', 'np.percentile', (['value', '(25)'], {}), '(value, 25)\n', (134, 145), True, 'import numpy as np\n'), ((1461, 1510), 'numpy.nanstd', 'np.nanstd', (['cv_avail_values'], {'axis': '(1)', 'ddof': 'std_ddof'}), '(cv_avail_values, axis=1, ddof=std_ddof)\n', (1470, 1510), True, 'import numpy as np\n'), ((1513, 1548), 'numpy.nanmean', 'np.nanmean', (['cv_avail_values'], {'axis': '(1)'}), '(cv_avail_values, axis=1)\n', (1523, 1548), True, 'import numpy as np\n'), ((1628, 1648), 'numpy.zeros', 'np.zeros', (['sample_num'], {}), '(sample_num)\n', (1636, 1648), True, 'import numpy as np\n'), ((1847, 1868), 'numpy.isnan', 'np.isnan', (['value_array'], {}), '(value_array)\n', (1855, 1868), True, 'import numpy as np\n'), ((2305, 2357), 'numpy.where', 'np.where', (['(kde_y[:apex_x_idx] < kde_y[apex_x_idx] / 2)'], {}), '(kde_y[:apex_x_idx] < kde_y[apex_x_idx] / 2)\n', (2313, 2357), True, 'import numpy as np\n'), ((2384, 2436), 'numpy.where', 'np.where', (['(kde_y[apex_x_idx:] < kde_y[apex_x_idx] / 2)'], {}), '(kde_y[apex_x_idx:] < kde_y[apex_x_idx] / 2)\n', (2392, 2436), True, 'import numpy as np\n'), ((1335, 1356), 'numpy.isnan', 'np.isnan', (['value_array'], {}), '(value_array)\n', (1343, 1356), True, 'import numpy as np\n')]
import pytest import fv3gfs.util import numpy as np from fv3gfs.util._boundary_utils import _shift_boundary_slice, get_boundary_slice def boundary_data(quantity, boundary_type, n_points, interior=True): boundary_slice = get_boundary_slice( quantity.dims, quantity.origin, quantity.extent, quantity.data.shape, boundary_type, n_points, interior, ) return quantity.data[tuple(boundary_slice)] @pytest.mark.cpu_only def test_boundary_data_1_by_1_array_1_halo(): quantity = fv3gfs.util.Quantity( np.random.randn(3, 3), dims=[fv3gfs.util.Y_DIM, fv3gfs.util.X_DIM], units="m", origin=(1, 1), extent=(1, 1), ) for side in ( fv3gfs.util.WEST, fv3gfs.util.EAST, fv3gfs.util.NORTH, fv3gfs.util.SOUTH, ): assert ( boundary_data(quantity, side, n_points=1, interior=True) == quantity.data[1, 1] ) assert ( boundary_data(quantity, fv3gfs.util.NORTH, n_points=1, interior=False) == quantity.data[2, 1] ) assert ( boundary_data(quantity, fv3gfs.util.SOUTH, n_points=1, interior=False) == quantity.data[0, 1] ) assert ( boundary_data(quantity, fv3gfs.util.WEST, n_points=1, interior=False) == quantity.data[1, 0] ) assert ( boundary_data(quantity, fv3gfs.util.EAST, n_points=1, interior=False) == quantity.data[1, 2] ) def test_boundary_data_3d_array_1_halo_z_offset_origin(numpy): quantity = fv3gfs.util.Quantity( numpy.random.randn(2, 3, 3), dims=[fv3gfs.util.Z_DIM, fv3gfs.util.Y_DIM, fv3gfs.util.X_DIM], units="m", origin=(1, 1, 1), extent=(1, 1, 1), ) for side in ( fv3gfs.util.WEST, fv3gfs.util.EAST, fv3gfs.util.NORTH, fv3gfs.util.SOUTH, ): quantity.np.testing.assert_array_equal( boundary_data(quantity, side, n_points=1, interior=True), quantity.data[1, 1, 1], ) quantity.np.testing.assert_array_equal( boundary_data(quantity, fv3gfs.util.NORTH, n_points=1, interior=False), quantity.data[1, 2, 1], ) quantity.np.testing.assert_array_equal( boundary_data(quantity, fv3gfs.util.SOUTH, n_points=1, interior=False), quantity.data[1, 0, 1], ) quantity.np.testing.assert_array_equal( boundary_data(quantity, fv3gfs.util.WEST, n_points=1, interior=False), quantity.data[1, 1, 0], ) quantity.np.testing.assert_array_equal( boundary_data(quantity, fv3gfs.util.EAST, n_points=1, interior=False), quantity.data[1, 1, 2], ) @pytest.mark.cpu_only def test_boundary_data_2_by_2_array_2_halo(): quantity = fv3gfs.util.Quantity( np.random.randn(6, 6), dims=[fv3gfs.util.Y_DIM, fv3gfs.util.X_DIM], units="m", origin=(2, 2), extent=(2, 2), ) for side in ( fv3gfs.util.WEST, fv3gfs.util.EAST, fv3gfs.util.NORTH, fv3gfs.util.SOUTH, ): np.testing.assert_array_equal( boundary_data(quantity, side, n_points=2, interior=True), quantity.data[2:4, 2:4], ) quantity.np.testing.assert_array_equal( boundary_data(quantity, fv3gfs.util.NORTH, n_points=1, interior=True), quantity.data[3:4, 2:4], ) quantity.np.testing.assert_array_equal( boundary_data(quantity, fv3gfs.util.NORTH, n_points=1, interior=False), quantity.data[4:5, 2:4], ) quantity.np.testing.assert_array_equal( boundary_data(quantity, fv3gfs.util.NORTH, n_points=2, interior=False), quantity.data[4:6, 2:4], ) quantity.np.testing.assert_array_equal( boundary_data(quantity, fv3gfs.util.SOUTH, n_points=1, interior=True), quantity.data[2:3, 2:4], ) quantity.np.testing.assert_array_equal( boundary_data(quantity, fv3gfs.util.SOUTH, n_points=1, interior=False), quantity.data[1:2, 2:4], ) quantity.np.testing.assert_array_equal( boundary_data(quantity, fv3gfs.util.SOUTH, n_points=2, interior=False), quantity.data[0:2, 2:4], ) quantity.np.testing.assert_array_equal( boundary_data(quantity, fv3gfs.util.WEST, n_points=2, interior=False), quantity.data[2:4, 0:2], ) quantity.np.testing.assert_array_equal( boundary_data(quantity, fv3gfs.util.WEST, n_points=1, interior=True), quantity.data[2:4, 2:3], ) quantity.np.testing.assert_array_equal( boundary_data(quantity, fv3gfs.util.WEST, n_points=1, interior=False), quantity.data[2:4, 1:2], ) quantity.np.testing.assert_array_equal( boundary_data(quantity, fv3gfs.util.EAST, n_points=1, interior=False), quantity.data[2:4, 4:5], ) quantity.np.testing.assert_array_equal( boundary_data(quantity, fv3gfs.util.EAST, n_points=2, interior=False), quantity.data[2:4, 4:6], ) quantity.np.testing.assert_array_equal( boundary_data(quantity, fv3gfs.util.EAST, n_points=1, interior=True), quantity.data[2:4, 3:4], ) @pytest.mark.parametrize( "dim, origin, extent, boundary_type, slice_object, reference", [ pytest.param( fv3gfs.util.X_DIM, 1, 3, fv3gfs.util.WEST, slice(None, None), slice(1, 4), id="none_is_changed", ), pytest.param( fv3gfs.util.Y_DIM, 1, 3, fv3gfs.util.WEST, slice(None, None), slice(1, 4), id="perpendicular_none_is_changed", ), pytest.param( fv3gfs.util.X_DIM, 1, 3, fv3gfs.util.WEST, slice(0, 1), slice(1, 2), id="shift_to_start", ), pytest.param( fv3gfs.util.X_DIM, 1, 3, fv3gfs.util.WEST, slice(0, 2), slice(1, 3), id="shift_larger_to_start", ), pytest.param( fv3gfs.util.X_DIM, 1, 3, fv3gfs.util.EAST, slice(0, 1), slice(4, 5), id="shift_to_end", ), pytest.param( fv3gfs.util.X_INTERFACE_DIM, 1, 3, fv3gfs.util.WEST, slice(0, 1), slice(1, 2), id="shift_interface_to_start", ), pytest.param( fv3gfs.util.X_INTERFACE_DIM, 1, 3, fv3gfs.util.EAST, slice(0, 1), slice(4, 5), id="shift_interface_to_end", ), pytest.param( fv3gfs.util.Y_DIM, 2, 4, fv3gfs.util.SOUTH, slice(0, 1), slice(2, 3), id="shift_y_to_start", ), pytest.param( fv3gfs.util.Y_DIM, 2, 4, fv3gfs.util.NORTH, slice(0, 1), slice(6, 7), id="shift_y_to_end", ), ], ) @pytest.mark.cpu_only def test_shift_boundary_slice( dim, origin, extent, boundary_type, slice_object, reference ): result = _shift_boundary_slice(dim, origin, extent, boundary_type, slice_object) assert result == reference
[ "fv3gfs.util._boundary_utils.get_boundary_slice", "numpy.random.randn", "fv3gfs.util._boundary_utils._shift_boundary_slice" ]
[((226, 353), 'fv3gfs.util._boundary_utils.get_boundary_slice', 'get_boundary_slice', (['quantity.dims', 'quantity.origin', 'quantity.extent', 'quantity.data.shape', 'boundary_type', 'n_points', 'interior'], {}), '(quantity.dims, quantity.origin, quantity.extent,\n quantity.data.shape, boundary_type, n_points, interior)\n', (244, 353), False, 'from fv3gfs.util._boundary_utils import _shift_boundary_slice, get_boundary_slice\n'), ((7407, 7478), 'fv3gfs.util._boundary_utils._shift_boundary_slice', '_shift_boundary_slice', (['dim', 'origin', 'extent', 'boundary_type', 'slice_object'], {}), '(dim, origin, extent, boundary_type, slice_object)\n', (7428, 7478), False, 'from fv3gfs.util._boundary_utils import _shift_boundary_slice, get_boundary_slice\n'), ((576, 597), 'numpy.random.randn', 'np.random.randn', (['(3)', '(3)'], {}), '(3, 3)\n', (591, 597), True, 'import numpy as np\n'), ((2845, 2866), 'numpy.random.randn', 'np.random.randn', (['(6)', '(6)'], {}), '(6, 6)\n', (2860, 2866), True, 'import numpy as np\n')]
#!/usr/bin/env python3 """ A simple test script for the shrinking module. Syntax: ./test.py m n Each run creates an invalid correlation matrix of order m+n, and then calls all five shrinking algorithms and times them. Finally, it draws a plot showing how the minimal eigenvalue of `S(alpha)` changes as `alpha` goes from 0 to 1. If not too big, other eigenvalues are shown as well. Created by <NAME> <<EMAIL>> """ import numpy as np import scipy.linalg from time import time from sys import argv, exit import matplotlib.pyplot as plt import shrinking # Set to False in order to display the other eigenvalues as well. # This rarely looks good, because the smallest eigenvalue is usually # of a too small order of magnitude in comparison with the other # eigenvalues. displayOnlyLambdaMin = True def randcorr(n, dof=None): """ Return a random correlation matrix of order `n` and rank `dof`. Written by <NAME> and taken from http://permalink.gmane.org/gmane.comp.python.scientific.devel/9657 """ if dof is None: dof = n vecs = np.random.randn(n, dof) vecs /= np.sqrt((vecs*vecs).sum(axis=-1))[:,None] M = np.matrix(np.dot(vecs, vecs.T)) np.fill_diagonal(M, 1) return M def mkmatrix(m, n): """ Return a random invalid correlation matrix of order `m+n` with a positive definite top left block of order `m`. """ while True: A = randcorr(m) #B = randcorr(n) B = np.identity(n) Y = np.matrix(np.random.randn(m, n) / (m+n)**1.2) M0 = np.bmat([[A, Y], [Y.T, B]]) if not shrinking.checkPD(M0, False): return M0 def timing(st): return time() - st def run(m=10, n=10): """ Run a single test: - generate a random invalid correlation matrix of order m+n, - shrink it with all 5 methods, - draw a graph :math:`\\alpha \\mapsto \\lambda_{\\min}(S(\\alpha))`. """ M0 = mkmatrix(m, n) st = time() print("Bisection: %.6f (%.5f sec)" % (shrinking.bisection(M0, fbs=m), timing(st))) st = time() print("BisectionFB: %.6f (%.5f sec)" % (shrinking.bisectionFB(M0, fbSize=m), timing(st))) st = time() print("Newton: %.6f (%.5f sec)" % (shrinking.newton(M0, fbs=m), timing(st))) st = time() print("GEP: %.6f (%.5f sec)" % (shrinking.GEP(M0, fbs=m), timing(st))) st = time() print("GEPFB: %.6f (%.5f sec)" % (shrinking.GEPFB(M0, fbSize=m), timing(st))) alphas = np.linspace(0, 1, 20) Svalues = np.array([ list(scipy.linalg.eigvalsh( shrinking.SFB(M0, m, alpha), check_finite = False ) for alpha in alphas) ]).transpose() plt.plot(alphas, Svalues[0]) if not displayOnlyLambdaMin: for p in range(1, n): plt.plot(alphas, Svalues[p], color="0.71") plt.axhline(color='black') alpha = shrinking.bisectionFB(M0, fbSize=m) plt.plot([alpha], [0], 'rD') # Parameters for plt.annotate taken from # http://stackoverflow.com/a/5147430/1667018 plt.annotate( r"$\alpha_*$", xy=(alpha, 0), xytext=(-20, 20), textcoords='offset points', ha='right', va='bottom', bbox = dict(boxstyle='round,pad=0.5', fc='#ffffb0', alpha=0.7), arrowprops=dict(arrowstyle='->', connectionstyle='arc3,rad=0') ) if displayOnlyLambdaMin: plt.legend([r"$\lambda_{\min}$"], loc='lower right') else: plt.legend([r"$\lambda_{\min}$", r"$\lambda > \lambda_{\min}$"], loc='lower right') x1,x2,y1,y2 = plt.axis() plt.xlabel(r"$\alpha$", fontsize=17) if displayOnlyLambdaMin: plt.suptitle(r"$\alpha \mapsto \lambda_{\min}(S(\alpha))$", fontsize=23) plt.ylabel(r"$\lambda_{\min}(S(\alpha))$", fontsize=17) else: plt.suptitle(r"$\alpha \mapsto \lambda(S(\alpha))$", fontsize=23) ym = max(map(abs, [Svalues[0][0], 10 * Svalues[0][-1]])) plt.axis((x1, x2, Svalues[0][0], 5 * ym)) plt.ylabel(r"$\lambda(S(\alpha))$", fontsize=17) plt.subplots_adjust(left=0.17, right=0.97) plt.show() if __name__ == "__main__": if len(argv) != 3: print("Syntax: ./test.py m n") exit(1) run(int(argv[1]), int(argv[2]))
[ "matplotlib.pyplot.suptitle", "shrinking.GEPFB", "shrinking.checkPD", "numpy.random.randn", "shrinking.GEP", "shrinking.bisectionFB", "numpy.identity", "numpy.bmat", "shrinking.bisection", "numpy.linspace", "matplotlib.pyplot.axhline", "numpy.fill_diagonal", "matplotlib.pyplot.show", "shri...
[((1071, 1094), 'numpy.random.randn', 'np.random.randn', (['n', 'dof'], {}), '(n, dof)\n', (1086, 1094), True, 'import numpy as np\n'), ((1193, 1215), 'numpy.fill_diagonal', 'np.fill_diagonal', (['M', '(1)'], {}), '(M, 1)\n', (1209, 1215), True, 'import numpy as np\n'), ((1956, 1962), 'time.time', 'time', ([], {}), '()\n', (1960, 1962), False, 'from time import time\n'), ((2062, 2068), 'time.time', 'time', ([], {}), '()\n', (2066, 2068), False, 'from time import time\n'), ((2173, 2179), 'time.time', 'time', ([], {}), '()\n', (2177, 2179), False, 'from time import time\n'), ((2276, 2282), 'time.time', 'time', ([], {}), '()\n', (2280, 2282), False, 'from time import time\n'), ((2376, 2382), 'time.time', 'time', ([], {}), '()\n', (2380, 2382), False, 'from time import time\n'), ((2485, 2506), 'numpy.linspace', 'np.linspace', (['(0)', '(1)', '(20)'], {}), '(0, 1, 20)\n', (2496, 2506), True, 'import numpy as np\n'), ((2684, 2712), 'matplotlib.pyplot.plot', 'plt.plot', (['alphas', 'Svalues[0]'], {}), '(alphas, Svalues[0])\n', (2692, 2712), True, 'import matplotlib.pyplot as plt\n'), ((2835, 2861), 'matplotlib.pyplot.axhline', 'plt.axhline', ([], {'color': '"""black"""'}), "(color='black')\n", (2846, 2861), True, 'import matplotlib.pyplot as plt\n'), ((2875, 2910), 'shrinking.bisectionFB', 'shrinking.bisectionFB', (['M0'], {'fbSize': 'm'}), '(M0, fbSize=m)\n', (2896, 2910), False, 'import shrinking\n'), ((2915, 2943), 'matplotlib.pyplot.plot', 'plt.plot', (['[alpha]', '[0]', '"""rD"""'], {}), "([alpha], [0], 'rD')\n", (2923, 2943), True, 'import matplotlib.pyplot as plt\n'), ((3542, 3552), 'matplotlib.pyplot.axis', 'plt.axis', ([], {}), '()\n', (3550, 3552), True, 'import matplotlib.pyplot as plt\n'), ((3557, 3593), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""$\\\\alpha$"""'], {'fontsize': '(17)'}), "('$\\\\alpha$', fontsize=17)\n", (3567, 3593), True, 'import matplotlib.pyplot as plt\n'), ((4028, 4070), 'matplotlib.pyplot.subplots_adjust', 'plt.subplots_adjust', ([], {'left': '(0.17)', 'right': '(0.97)'}), '(left=0.17, right=0.97)\n', (4047, 4070), True, 'import matplotlib.pyplot as plt\n'), ((4076, 4086), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (4084, 4086), True, 'import matplotlib.pyplot as plt\n'), ((1167, 1187), 'numpy.dot', 'np.dot', (['vecs', 'vecs.T'], {}), '(vecs, vecs.T)\n', (1173, 1187), True, 'import numpy as np\n'), ((1464, 1478), 'numpy.identity', 'np.identity', (['n'], {}), '(n)\n', (1475, 1478), True, 'import numpy as np\n'), ((1550, 1577), 'numpy.bmat', 'np.bmat', (['[[A, Y], [Y.T, B]]'], {}), '([[A, Y], [Y.T, B]])\n', (1557, 1577), True, 'import numpy as np\n'), ((1673, 1679), 'time.time', 'time', ([], {}), '()\n', (1677, 1679), False, 'from time import time\n'), ((3368, 3421), 'matplotlib.pyplot.legend', 'plt.legend', (["['$\\\\lambda_{\\\\min}$']"], {'loc': '"""lower right"""'}), "(['$\\\\lambda_{\\\\min}$'], loc='lower right')\n", (3378, 3421), True, 'import matplotlib.pyplot as plt\n'), ((3439, 3530), 'matplotlib.pyplot.legend', 'plt.legend', (["['$\\\\lambda_{\\\\min}$', '$\\\\lambda > \\\\lambda_{\\\\min}$']"], {'loc': '"""lower right"""'}), "(['$\\\\lambda_{\\\\min}$', '$\\\\lambda > \\\\lambda_{\\\\min}$'], loc=\n 'lower right')\n", (3449, 3530), True, 'import matplotlib.pyplot as plt\n'), ((3631, 3707), 'matplotlib.pyplot.suptitle', 'plt.suptitle', (['"""$\\\\alpha \\\\mapsto \\\\lambda_{\\\\min}(S(\\\\alpha))$"""'], {'fontsize': '(23)'}), "('$\\\\alpha \\\\mapsto \\\\lambda_{\\\\min}(S(\\\\alpha))$', fontsize=23)\n", (3643, 3707), True, 'import matplotlib.pyplot as plt\n'), ((3712, 3769), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""$\\\\lambda_{\\\\min}(S(\\\\alpha))$"""'], {'fontsize': '(17)'}), "('$\\\\lambda_{\\\\min}(S(\\\\alpha))$', fontsize=17)\n", (3722, 3769), True, 'import matplotlib.pyplot as plt\n'), ((3786, 3854), 'matplotlib.pyplot.suptitle', 'plt.suptitle', (['"""$\\\\alpha \\\\mapsto \\\\lambda(S(\\\\alpha))$"""'], {'fontsize': '(23)'}), "('$\\\\alpha \\\\mapsto \\\\lambda(S(\\\\alpha))$', fontsize=23)\n", (3798, 3854), True, 'import matplotlib.pyplot as plt\n'), ((3925, 3966), 'matplotlib.pyplot.axis', 'plt.axis', (['(x1, x2, Svalues[0][0], 5 * ym)'], {}), '((x1, x2, Svalues[0][0], 5 * ym))\n', (3933, 3966), True, 'import matplotlib.pyplot as plt\n'), ((3975, 4024), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""$\\\\lambda(S(\\\\alpha))$"""'], {'fontsize': '(17)'}), "('$\\\\lambda(S(\\\\alpha))$', fontsize=17)\n", (3985, 4024), True, 'import matplotlib.pyplot as plt\n'), ((4187, 4194), 'sys.exit', 'exit', (['(1)'], {}), '(1)\n', (4191, 4194), False, 'from sys import argv, exit\n'), ((1593, 1621), 'shrinking.checkPD', 'shrinking.checkPD', (['M0', '(False)'], {}), '(M0, False)\n', (1610, 1621), False, 'import shrinking\n'), ((2788, 2830), 'matplotlib.pyplot.plot', 'plt.plot', (['alphas', 'Svalues[p]'], {'color': '"""0.71"""'}), "(alphas, Svalues[p], color='0.71')\n", (2796, 2830), True, 'import matplotlib.pyplot as plt\n'), ((1501, 1522), 'numpy.random.randn', 'np.random.randn', (['m', 'n'], {}), '(m, n)\n', (1516, 1522), True, 'import numpy as np\n'), ((2007, 2037), 'shrinking.bisection', 'shrinking.bisection', (['M0'], {'fbs': 'm'}), '(M0, fbs=m)\n', (2026, 2037), False, 'import shrinking\n'), ((2113, 2148), 'shrinking.bisectionFB', 'shrinking.bisectionFB', (['M0'], {'fbSize': 'm'}), '(M0, fbSize=m)\n', (2134, 2148), False, 'import shrinking\n'), ((2224, 2251), 'shrinking.newton', 'shrinking.newton', (['M0'], {'fbs': 'm'}), '(M0, fbs=m)\n', (2240, 2251), False, 'import shrinking\n'), ((2327, 2351), 'shrinking.GEP', 'shrinking.GEP', (['M0'], {'fbs': 'm'}), '(M0, fbs=m)\n', (2340, 2351), False, 'import shrinking\n'), ((2427, 2456), 'shrinking.GEPFB', 'shrinking.GEPFB', (['M0'], {'fbSize': 'm'}), '(M0, fbSize=m)\n', (2442, 2456), False, 'import shrinking\n'), ((2580, 2607), 'shrinking.SFB', 'shrinking.SFB', (['M0', 'm', 'alpha'], {}), '(M0, m, alpha)\n', (2593, 2607), False, 'import shrinking\n')]
import numpy import IPython class S2N(): def __init__(self):#This class can only be inherited from pass def imageRegions(image,sig,sigfloor=0.5): image[image/sig<significancefloor]=0 masks, multiplicity = ndimage.measurements.label(image) labels=numpy.arange(1, multiplicity+1) def SNfunc(self,data,sig,significancefloor=0.5): D=data.ravel() S=sig.ravel() args=numpy.argsort(-D/S) D=numpy.take(D,args) S=numpy.take(S,args) Dsum=numpy.cumsum(D) Ssum=numpy.cumsum(S**2)**0.5 SN=(Dsum/Ssum).max() #regional SN import scipy.ndimage as ndimage #data[data/sig<significancefloor] = 0 masks, multiplicity = ndimage.measurements.label(data) labels = numpy.arange(1, multiplicity+1) SNs = numpy.zeros(multiplicity+1) #SNs = numpy.array(multiplicity+1) # check this SNs[0]=SN for i in range(multiplicity): D=data[masks==i+1].ravel() S=sig[masks==i+1].ravel() args=numpy.argsort(-D/S) D=numpy.take(D,args) S=numpy.take(S,args) Dsum=numpy.cumsum(D) Ssum=numpy.cumsum(S**2)**0.5 SNi=(Dsum/Ssum).max() SNs[i+1]=SNi SNs=-numpy.sort(-SNs) return SNs def SourceMetaData(self,SNcutA=15,magcut=3,SNcutB=[10,8]): self.mag={} self.msrc={} self.bestband={} self.passfail={} self.resolved={} for src in self.sourcenumbers: self.resolved[src]={} SNr={} self.mag[src]=self.magnification[src] self.msrc[src]={} for band in self.bands: # if self.seeing[band]==0: self.msrc[src][band]=self.totallensedsrcmag[src][band] if self.mag[src]*self.rs[src]>(self.seeing[band]/self.pixelsize): self.resolved[src][band]=True SNindex=0 else: self.resolved[src][band]=False SNindex=2 try: SNr[band]=self.SN[src][band][SNindex] except IndexError: SNr[band]=0 except KeyError: SNr[band]=0 # else: # self.SN[src][band]=[0,0,0] # self.msrc[src][band]=[99] # self.resolved[src][band]=False # SNr[band]=0 self.bestband[src],dummy = max(SNr.iteritems(), key=lambda x:x[1]) self.passfail[src]=False try: if self.SN[src][self.bestband[src]][2]>min(SNcutB) and \ self.SN[src][self.bestband[src]][1]>max(SNcutB): self.passfail[src]=True ltype=1 except IndexError: pass try: #print self.SN[src][self.bestband[src]][0],SNcutA,self.mag[src],magcut,self.resolved[src][self.bestband[src]] if self.SN[src][self.bestband[src]][0]>SNcutA and \ (self.mag[src]>magcut) and self.resolved[src][self.bestband[src]]: self.passfail[src]=True ltype=2 except IndexError: pass if self.SeeingTest(src,self.bestband[src]) ==False: self.passfail[src]=False #debugger #for src in self.sourcenumbers: # print src,self.passfail[src],self.SeeingTest(src,self.bestband[src]),self.SN[src][self.bestband[src]][0],self.resolved[src][self.bestband[src]],self.mag[src],ltype return self.mag,self.msrc,self.SN,self.bestband,self.passfail #=========================================================================== def RingFinderSN(self, bands=["g_SDSS","i_SDSS"],repair=True,mode="crossconvolve",SNcutA=15,magcut=3,SNcutB=[10,8],runringfinder=False,mustbeseen=False): self.rfpf={} for src in self.sourcenumbers: self.SNRF[src]=[0] self.rfpf[src]=False try: if self.seeing[bands[0]]==0: return self.rfpf,self.SNRF except KeyError: return self.rfpf,self.SNRF try: if self.seeing[bands[1]]==0: return self.rfpf,self.SNRF except KeyError: return self.rfpf,self.SNRF if mode=="crossconvolve": seeing=(self.seeing[bands[1]]**2+self.seeing[bands[0]]**2)**.5 for band in bands: self.psfFFT[band]=None self.psfscale[band]=seeing/2.355 self.psf[band]= numpy.exp(-0.5*self.r2/(self.psfscale[band]/self.pixelsize)**2) self.psf[band]/=numpy.sum(self.psf[band]) self.ObserveLens(bands=bands) else: seeing=self.seeing[bands[0]] self.seeing["RF"]=seeing seen=False for src in self.sourcenumbers: if self.SeeingTest(src,"RF"): seen=True if mustbeseen: seen=True if seen==False: return [self.rfpf,self.SNRF] assert (self.psf[bands[0]]-self.psf[bands[1]]).sum()==0, "psf missmatch - can't run ringfinder" B=self.image[bands[0]] R=self.image[bands[1]] sB=self.sigma[bands[0]] sR=self.sigma[bands[1]] r=self.r2**0.5 r*=self.pixelsize mask=((r<2.7) & (r>0.5)) alpha=B[mask].sum()*1./R[mask].sum() self.D=B-alpha*R self.S=(sB**2+(alpha*sR)**2)**.5 self.fakeResidual[0]["RF"]=self.D for src in self.sourcenumbers: self.SNRF[src]=self.SNfunc(self.convolvedsrc[src]["g_SDSS"]-alpha*self.convolvedsrc[src]["i_SDSS"],self.S) d=self.convolvedsrc[src]["g_SDSS"]-alpha*self.convolvedsrc[src]["i_SDSS"] d+=(numpy.random.randn(self.side,self.side)*(self.S)) self.fakeResidual[src]["RF"]=d if self.mag[src]*self.rs[src]>(seeing/self.pixelsize): self.resolved[src]["RF"]=True else: self.resolved[src]["RF"]=False self.rfpf[src]=False try: if self.SNRF[src][2]>min(SNcutB) and \ self.SNRF[src][1]>max(SNcutB): self.rfpf[src]=True except IndexError: pass try: if self.SNRF[src][0]>SNcutA \ and self.mag[src]>magcut \ and self.mag[src]*self.rs[src]>(seeing/self.pixelsize): self.rfpf[src]=True except IndexError: pass if self.SeeingTest(src,"RF")==False: self.rfpf[src]=False self.passfail[src]=False if runringfinder: import RingFinder RF=RingFinder.RingFinder(B,\ R,\ sB,\ sR,\ self.pixelsize,\ self.zeromagcounts["g_SDSS"], self.zeromagcounts["i_SDSS"]) RFo=RF.ringfind() self.D=RF.D*1 return RFo,self.rfpf,self.SNRF return self.rfpf,self.SNRF
[ "numpy.sum", "numpy.random.randn", "scipy.ndimage.measurements.label", "numpy.zeros", "numpy.argsort", "numpy.cumsum", "numpy.sort", "numpy.take", "numpy.arange", "numpy.exp", "RingFinder.RingFinder" ]
[((238, 271), 'scipy.ndimage.measurements.label', 'ndimage.measurements.label', (['image'], {}), '(image)\n', (264, 271), True, 'import scipy.ndimage as ndimage\n'), ((287, 320), 'numpy.arange', 'numpy.arange', (['(1)', '(multiplicity + 1)'], {}), '(1, multiplicity + 1)\n', (299, 320), False, 'import numpy\n'), ((449, 470), 'numpy.argsort', 'numpy.argsort', (['(-D / S)'], {}), '(-D / S)\n', (462, 470), False, 'import numpy\n'), ((479, 498), 'numpy.take', 'numpy.take', (['D', 'args'], {}), '(D, args)\n', (489, 498), False, 'import numpy\n'), ((508, 527), 'numpy.take', 'numpy.take', (['S', 'args'], {}), '(S, args)\n', (518, 527), False, 'import numpy\n'), ((540, 555), 'numpy.cumsum', 'numpy.cumsum', (['D'], {}), '(D)\n', (552, 555), False, 'import numpy\n'), ((761, 793), 'scipy.ndimage.measurements.label', 'ndimage.measurements.label', (['data'], {}), '(data)\n', (787, 793), True, 'import scipy.ndimage as ndimage\n'), ((811, 844), 'numpy.arange', 'numpy.arange', (['(1)', '(multiplicity + 1)'], {}), '(1, multiplicity + 1)\n', (823, 844), False, 'import numpy\n'), ((857, 886), 'numpy.zeros', 'numpy.zeros', (['(multiplicity + 1)'], {}), '(multiplicity + 1)\n', (868, 886), False, 'import numpy\n'), ((569, 589), 'numpy.cumsum', 'numpy.cumsum', (['(S ** 2)'], {}), '(S ** 2)\n', (581, 589), False, 'import numpy\n'), ((1092, 1113), 'numpy.argsort', 'numpy.argsort', (['(-D / S)'], {}), '(-D / S)\n', (1105, 1113), False, 'import numpy\n'), ((1126, 1145), 'numpy.take', 'numpy.take', (['D', 'args'], {}), '(D, args)\n', (1136, 1145), False, 'import numpy\n'), ((1159, 1178), 'numpy.take', 'numpy.take', (['S', 'args'], {}), '(S, args)\n', (1169, 1178), False, 'import numpy\n'), ((1195, 1210), 'numpy.cumsum', 'numpy.cumsum', (['D'], {}), '(D)\n', (1207, 1210), False, 'import numpy\n'), ((1324, 1340), 'numpy.sort', 'numpy.sort', (['(-SNs)'], {}), '(-SNs)\n', (1334, 1340), False, 'import numpy\n'), ((1228, 1248), 'numpy.cumsum', 'numpy.cumsum', (['(S ** 2)'], {}), '(S ** 2)\n', (1240, 1248), False, 'import numpy\n'), ((4768, 4839), 'numpy.exp', 'numpy.exp', (['(-0.5 * self.r2 / (self.psfscale[band] / self.pixelsize) ** 2)'], {}), '(-0.5 * self.r2 / (self.psfscale[band] / self.pixelsize) ** 2)\n', (4777, 4839), False, 'import numpy\n'), ((4864, 4889), 'numpy.sum', 'numpy.sum', (['self.psf[band]'], {}), '(self.psf[band])\n', (4873, 4889), False, 'import numpy\n'), ((5977, 6017), 'numpy.random.randn', 'numpy.random.randn', (['self.side', 'self.side'], {}), '(self.side, self.side)\n', (5995, 6017), False, 'import numpy\n'), ((6958, 7074), 'RingFinder.RingFinder', 'RingFinder.RingFinder', (['B', 'R', 'sB', 'sR', 'self.pixelsize', "self.zeromagcounts['g_SDSS']", "self.zeromagcounts['i_SDSS']"], {}), "(B, R, sB, sR, self.pixelsize, self.zeromagcounts[\n 'g_SDSS'], self.zeromagcounts['i_SDSS'])\n", (6979, 7074), False, 'import RingFinder\n')]
import argparse import json from collections import OrderedDict as odict from pathlib import Path import h5py import numpy as np def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument( "--dataroot", type=str, default="data", help="change datasets root path") parser.add_argument( "--howto100m", action="store_true") args = parser.parse_args() dataset_path = Path(args.dataroot) / "youcook2" features_file = (dataset_path / ( "video_feat_100m.h5" if args.howto100m else "video_feat_2d3d.h5")) meta_file = dataset_path / "meta_{}.json".format( "100m" if args.howto100m else "2d3d") meta_in_file = (dataset_path / "captions" / "youcookii_annotations_trainval.json") with meta_in_file.open("rt", encoding="utf8") as fh: meta_raw = json.load(fh)["database"] vid_h5 = h5py.File(features_file, "r") split_map = { "training": "train", "validation": "val" } meta_dict = odict() for idx, meta in meta_raw.items(): duration_sec = meta["duration"] split = split_map[meta["subset"]] num_frames = int(vid_h5[idx].shape[0]) fps = num_frames / duration_sec segs = [] for seg in meta["annotations"]: time_start, time_stop = seg["segment"] assert time_stop > time_start start_frame = int(np.floor(fps * time_start)) stop_frame = int(np.ceil(fps * time_stop)) + 1 if stop_frame >= num_frames: stop_frame = num_frames - 1 num_frames_seg = stop_frame - start_frame + 1 narration = seg["sentence"] seg_new = { "narration": narration, "start_frame": start_frame, "num_frames": num_frames_seg } segs.append(seg_new) meta_dict[idx] = odict([ ("split", split), ("data_id", idx), ("num_frames", num_frames), ("segments", segs), ]) json.dump(meta_dict, meta_file.open("wt", encoding="utf8"), sort_keys=True) print(f"wrote {meta_file}") if __name__ == '__main__': main()
[ "h5py.File", "json.load", "argparse.ArgumentParser", "numpy.ceil", "numpy.floor", "pathlib.Path", "collections.OrderedDict" ]
[((157, 201), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '__doc__'}), '(description=__doc__)\n', (180, 201), False, 'import argparse\n'), ((904, 933), 'h5py.File', 'h5py.File', (['features_file', '"""r"""'], {}), "(features_file, 'r')\n", (913, 933), False, 'import h5py\n'), ((1031, 1038), 'collections.OrderedDict', 'odict', ([], {}), '()\n', (1036, 1038), True, 'from collections import OrderedDict as odict\n'), ((436, 455), 'pathlib.Path', 'Path', (['args.dataroot'], {}), '(args.dataroot)\n', (440, 455), False, 'from pathlib import Path\n'), ((1923, 2019), 'collections.OrderedDict', 'odict', (["[('split', split), ('data_id', idx), ('num_frames', num_frames), (\n 'segments', segs)]"], {}), "([('split', split), ('data_id', idx), ('num_frames', num_frames), (\n 'segments', segs)])\n", (1928, 2019), True, 'from collections import OrderedDict as odict\n'), ((865, 878), 'json.load', 'json.load', (['fh'], {}), '(fh)\n', (874, 878), False, 'import json\n'), ((1428, 1454), 'numpy.floor', 'np.floor', (['(fps * time_start)'], {}), '(fps * time_start)\n', (1436, 1454), True, 'import numpy as np\n'), ((1485, 1509), 'numpy.ceil', 'np.ceil', (['(fps * time_stop)'], {}), '(fps * time_stop)\n', (1492, 1509), True, 'import numpy as np\n')]
import lmfit import numpy as np from scraps.fitsS21 import utils def offset(freqs, re0, im0): """Complex offset re + j*im. Freqs vector is ignored, but required for lmfit Model.""" return re0 + 1j * im0 def mag(freqs, g0, g1, g2): """2nd order polynomial. References the freqs-array midpoint, which is important because the baseline coefs shouldn't drift around with changes in f0 due to power or temperature.""" x = utils.reduce_by_midpoint(freqs) return g0 + g1 * x + g2 * x ** 2 def phase(freqs, p0, p1, p2): """Angle in complex plane parameterized by 2nd order polynomial. References the freqs-array midpoint, which is important because the baseline coefs shouldn't drift around with changes in f0 due to power or temperature.""" x = utils.reduce_by_midpoint(freqs) phi = p0 + p1 * x + p2 * x ** 2 return np.exp(1j * phi) class ModelMagBaseline(lmfit.Model): __doc__ = ( "lmfit model that fits a 2nd order polynomial as a function of reduced frequency." + lmfit.models.COMMON_DOC ) def __init__(self, *args, **kwargs): super().__init__(mag, *args, **kwargs) def guess(self, data, freqs=None, mask=None, **kwargs): """Mask is an number for how many points to keep on each end. If int, then assumes number of points, if float then assumes percent of data. If None, keeps everything.""" if freqs is None: raise ValueError("Must pass a frequencies vector") mag_data = np.abs(data) xvals = utils.reduce_by_midpoint(freqs) masked_data = utils.mask_array_ends(mag_data, mask) masked_xvals = utils.mask_array_ends(xvals, mask) g2, g1, g0 = np.polyfit(masked_xvals, masked_data, 2) params = self.make_params(g2=g2, g1=g1, g0=g0) return lmfit.models.update_param_vals(params, self.prefix, **kwargs) class ModelPhaseBaseline(lmfit.Model): __doc__ = ( "lmfit model that fits a 2nd order polynomial to phase angle as a function of reduced frequency." + lmfit.models.COMMON_DOC ) def __init__(self, *args, **kwargs): super().__init__(phase, *args, **kwargs) def guess(self, data, freqs=None, mask=None, phase_step=None, **kwargs): """Treats phase angle as either a 1st or 2nd order polynomial. Passing a float to phase_step will cause that amount to be subtracted from the first half of the masked data prior to fitting a polynomial. This is useful if it's clear that the phase rolls sharply through either pi or 2pi, but it's also obvious there is some strong frequency-dependent behavior. Passing fit_quadratic_phase will cause the baseline to be modeled as a second-order polynomial. The default value for this is False.""" if freqs is None: raise ValueError("Must pass a frequencies vector") fit_quadratic_phase = kwargs.pop("fit_quadratic_phase", False) unwrap_phase = kwargs.pop("unwrap_phase", True) phase_data = np.angle(data) xvals = utils.reduce_by_midpoint(freqs) if unwrap_phase: phase_data = np.unwrap(phase_data) masked_data = utils.mask_array_ends(phase_data, mask) masked_xvals = utils.mask_array_ends(xvals, mask) if phase_step: step_vector = np.ones_like(masked_data) step_vector[-len(step_vector) // 2 :] = 0 step_vector *= phase_step masked_data -= step_vector if fit_quadratic_phase: p2, p1, p0 = np.polyfit(masked_xvals, masked_data, 2) else: p1, p0 = np.polyfit(masked_xvals, masked_data, 1) p2 = 0 params = self.make_params(p2=p2, p1=p1, p0=p0) if not fit_quadratic_phase: params[f"{self.prefix}p2"].set(vary=False) return lmfit.models.update_param_vals(params, self.prefix, **kwargs) class ModelComplexOffset(lmfit.Model): __doc__ = "lmfit model that fits a complex offset." + lmfit.models.COMMON_DOC def __init__(self, *args, **kwargs): super().__init__(offset, *args, **kwargs) def guess(self, data, freqs=None, mask=None, **kwargs): """Guesses the real and imaginary offsets as the mean of the masked real and imaginary parts of data, respectively.""" masked_data = utils.mask_array_ends(data, mask) re = np.real(masked_data).mean() im = np.imag(masked_data).mean() params = self.make_params(re=re, im=im) return lmfit.models.update_param_vals(params, self.prefix, **kwargs)
[ "scraps.fitsS21.utils.reduce_by_midpoint", "numpy.abs", "numpy.ones_like", "numpy.polyfit", "numpy.angle", "numpy.unwrap", "lmfit.models.update_param_vals", "numpy.imag", "scraps.fitsS21.utils.mask_array_ends", "numpy.exp", "numpy.real" ]
[((451, 482), 'scraps.fitsS21.utils.reduce_by_midpoint', 'utils.reduce_by_midpoint', (['freqs'], {}), '(freqs)\n', (475, 482), False, 'from scraps.fitsS21 import utils\n'), ((795, 826), 'scraps.fitsS21.utils.reduce_by_midpoint', 'utils.reduce_by_midpoint', (['freqs'], {}), '(freqs)\n', (819, 826), False, 'from scraps.fitsS21 import utils\n'), ((874, 892), 'numpy.exp', 'np.exp', (['(1.0j * phi)'], {}), '(1.0j * phi)\n', (880, 892), True, 'import numpy as np\n'), ((1523, 1535), 'numpy.abs', 'np.abs', (['data'], {}), '(data)\n', (1529, 1535), True, 'import numpy as np\n'), ((1552, 1583), 'scraps.fitsS21.utils.reduce_by_midpoint', 'utils.reduce_by_midpoint', (['freqs'], {}), '(freqs)\n', (1576, 1583), False, 'from scraps.fitsS21 import utils\n'), ((1607, 1644), 'scraps.fitsS21.utils.mask_array_ends', 'utils.mask_array_ends', (['mag_data', 'mask'], {}), '(mag_data, mask)\n', (1628, 1644), False, 'from scraps.fitsS21 import utils\n'), ((1668, 1702), 'scraps.fitsS21.utils.mask_array_ends', 'utils.mask_array_ends', (['xvals', 'mask'], {}), '(xvals, mask)\n', (1689, 1702), False, 'from scraps.fitsS21 import utils\n'), ((1725, 1765), 'numpy.polyfit', 'np.polyfit', (['masked_xvals', 'masked_data', '(2)'], {}), '(masked_xvals, masked_data, 2)\n', (1735, 1765), True, 'import numpy as np\n'), ((1838, 1899), 'lmfit.models.update_param_vals', 'lmfit.models.update_param_vals', (['params', 'self.prefix'], {}), '(params, self.prefix, **kwargs)\n', (1868, 1899), False, 'import lmfit\n'), ((3074, 3088), 'numpy.angle', 'np.angle', (['data'], {}), '(data)\n', (3082, 3088), True, 'import numpy as np\n'), ((3105, 3136), 'scraps.fitsS21.utils.reduce_by_midpoint', 'utils.reduce_by_midpoint', (['freqs'], {}), '(freqs)\n', (3129, 3136), False, 'from scraps.fitsS21 import utils\n'), ((3233, 3272), 'scraps.fitsS21.utils.mask_array_ends', 'utils.mask_array_ends', (['phase_data', 'mask'], {}), '(phase_data, mask)\n', (3254, 3272), False, 'from scraps.fitsS21 import utils\n'), ((3296, 3330), 'scraps.fitsS21.utils.mask_array_ends', 'utils.mask_array_ends', (['xvals', 'mask'], {}), '(xvals, mask)\n', (3317, 3330), False, 'from scraps.fitsS21 import utils\n'), ((3896, 3957), 'lmfit.models.update_param_vals', 'lmfit.models.update_param_vals', (['params', 'self.prefix'], {}), '(params, self.prefix, **kwargs)\n', (3926, 3957), False, 'import lmfit\n'), ((4392, 4425), 'scraps.fitsS21.utils.mask_array_ends', 'utils.mask_array_ends', (['data', 'mask'], {}), '(data, mask)\n', (4413, 4425), False, 'from scraps.fitsS21 import utils\n'), ((4574, 4635), 'lmfit.models.update_param_vals', 'lmfit.models.update_param_vals', (['params', 'self.prefix'], {}), '(params, self.prefix, **kwargs)\n', (4604, 4635), False, 'import lmfit\n'), ((3188, 3209), 'numpy.unwrap', 'np.unwrap', (['phase_data'], {}), '(phase_data)\n', (3197, 3209), True, 'import numpy as np\n'), ((3381, 3406), 'numpy.ones_like', 'np.ones_like', (['masked_data'], {}), '(masked_data)\n', (3393, 3406), True, 'import numpy as np\n'), ((3596, 3636), 'numpy.polyfit', 'np.polyfit', (['masked_xvals', 'masked_data', '(2)'], {}), '(masked_xvals, masked_data, 2)\n', (3606, 3636), True, 'import numpy as np\n'), ((3672, 3712), 'numpy.polyfit', 'np.polyfit', (['masked_xvals', 'masked_data', '(1)'], {}), '(masked_xvals, masked_data, 1)\n', (3682, 3712), True, 'import numpy as np\n'), ((4440, 4460), 'numpy.real', 'np.real', (['masked_data'], {}), '(masked_data)\n', (4447, 4460), True, 'import numpy as np\n'), ((4481, 4501), 'numpy.imag', 'np.imag', (['masked_data'], {}), '(masked_data)\n', (4488, 4501), True, 'import numpy as np\n')]
""" A2C model """ import os, sys import time import argparse import tensorflow.compat.v1 as tf import gym from drl_negotiation.env import SCMLEnv import drl_negotiation.utils as U import numpy as np import pickle from tqdm import tqdm from drl_negotiation.hyperparameters import * import logging class MADDPGModel: trained_model = None def __init__(self, env: SCMLEnv = None, policy=None, only_seller=ONLY_SELLER, logging_level = LOGGING_LEVEL, # training # trainer update steps n_steps=15, # learning rate lr=1e-2, # discount factor gamma=0.95, # model save dir save_dir=SAVE_DIR, # model name model_name=MODEL_NAME, # model save rate save_rate=SAVE_RATE, # model load dir load_dir='', # experiment name exp_name="", # batch size * max_episode_len = replay buffer batch_size=1, num_units=64, # env n_envs=1, # number of training episodes num_episodes=60, # max length of every episode max_episode_len=10, # number of adversaries num_adversaries=0, # policy of good agent good_policy="maddpg", # policy of adversary agent adv_policy="heuristic", # evaluation benchmark=False, benchmark_iters=1000, benchmark_dir="./benchmark_files/", restore=False, display=False, plots_dir="./learning_curves/", # init the model, used for evaluation _init_setup_model=False, save_trainers=SAVE_TRAINERS, **kwargs, ): self.policy = policy self.env = env self.only_seller = only_seller self.logging_level = logging_level # update trainer rate, belongs to training step self.n_steps = n_steps self.lr = lr self.gamma = gamma self.save_dir = save_dir self.save_rate = save_rate self.model_name = model_name self.load_dir = load_dir self.exp_name = exp_name self.batch_size = batch_size self.num_units = num_units # env self.n_envs = n_envs self.num_episodes = num_episodes self.max_episode_len = max_episode_len self.num_adversaries = num_adversaries self.good_policy = good_policy self.adv_policy = adv_policy # evaluation self.benchmark = benchmark self.benchmark_iters = benchmark_iters self.benchmark_dir = benchmark_dir self.restore = restore self.display = display self.plots_dir = plots_dir self.arglist = kwargs self.trainers = None if _init_setup_model: self.setup_model() self.save_trainers = save_trainers def setup_model(self): with U.single_threaded_session(): if not ONLY_SELLER: obs_shape_n = [] for i in range(self.env.n): obs_shape_n.append(self.env.observation_space[i].shape) obs_shape_n.append(self.env.observation_space[i+1].shape) else: obs_shape_n = [self.env.observation_space[i].shape for i in range(self.env.n)] num_adversaries = min(self.env.n, self.num_adversaries) arglist = argparse.Namespace(**{"good_policy": self.good_policy, "adv_policy": self.adv_policy, "lr": self.lr, "num_units": self.num_units, "batch_size": self.batch_size, "max_episode_len": self.max_episode_len, "gamma": self.gamma, "n_steps": self.n_steps }) self.trainers = U.get_trainers(self.env, num_adversaries, obs_shape_n, arglist) logging.info(f"Using good policy {self.good_policy} and adv policy {self.adv_policy}") # assert issubclass(self.policy, Policy), "Error: the input policy for the maddpg model must be an" \ # "instance of a2c.policy.Policy" # self.graph = tf.Graph() def _setup_learn(self): """ Check the environment """ if self.env is None: raise ValueError("Error: cannot train the model without a valid environment, please set an environment " "with set_env(self, env) method.") def learn(self, train_episodes=None): self._setup_learn() if train_episodes is not None: self.num_episodes = train_episodes with U.single_threaded_session(): if not ONLY_SELLER: obs_shape_n = [] for i in range(self.env.n): obs_shape_n.append(self.env.observation_space[i].shape) obs_shape_n.append(self.env.observation_space[i+1].shape) else: obs_shape_n = [self.env.observation_space[i].shape for i in range(self.env.n)] num_adversaries = min(self.env.n, self.num_adversaries) arglist = argparse.Namespace(**{"good_policy":self.good_policy, "adv_policy": self.adv_policy, "lr": self.lr, "num_units": self.num_units, "batch_size": self.batch_size, "max_episode_len": self.max_episode_len, "gamma": self.gamma, "n_steps": self.n_steps }) self.trainers = U.get_trainers(self.env, num_adversaries, obs_shape_n, arglist) logging.info(f"Using good policy {self.good_policy} and adv policy {self.adv_policy}") U.initialize() if self.load_dir == '': self.load_dir = self.save_dir saver = tf.train.Saver() if self.display or self.restore or self.benchmark: logging.info("Loading previous state...") #saver = tf.train.import_meta_graph(self.load_dir+self.model_name+'.meta') U.load_state(tf.train.latest_checkpoint(self.load_dir), saver=saver) if saver is None: saver = U.get_saver() episode_rewards = [0.0] agent_rewards = [[0.0] for _ in range(self.env.n)] final_ep_rewards = [] final_ep_ag_rewards = [] agent_info = [[[]]] obs_n = self.env.reset() episode_step = 0 current_episode = 0 train_step = 0 t_start = time.time() pbar = tqdm(total=self.num_episodes) while True: #print(f'episodes: {len(episode_rewards)}, train steps: {train_step}') action_n = self.predict(obs_n) clipped_action_n = action_n for i, _ in enumerate(self.env.action_space): if isinstance(_ , gym.spaces.Box): clipped_action_n[i] = np.clip(action_n[i], self.env.action_space[i].low, self.env.action_space[i].high) #print(f"action_n: {action_n}") new_obs_n, rew_n, done_n, info_n = self.env.step(clipped_action_n) episode_step +=1 done = all(done_n) terminal = (episode_step > self.max_episode_len) # experience for i, agent in enumerate(self.trainers): agent.experience(obs_n[i], action_n[i], rew_n[i], new_obs_n[i], done_n[i], terminal) obs_n = new_obs_n for i, rew in enumerate(rew_n): episode_rewards[-1] += rew if not ONLY_SELLER: agent_rewards[int(i / 2)][-1] += rew else: agent_rewards[i][-1] += rew if done or terminal: obs_n = self.env.reset() episode_step = 0 pbar.update(1) episode_rewards.append(0) for a in agent_rewards: a.append(0) agent_info.append([[]]) train_step += 1 # Evaluate, benchmarking learned policies if self.benchmark: for i, info in enumerate(info_n): agent_info[-1][i].append(info_n['n']) if train_step > self.benchmark_iters and (done or terminal): file_name = self.benchmark_dir + self.exp_name + '.pkl' logging.info("Finished benchmarking, now saving....") with open(file_name, 'wb') as fp: pickle.dump(agent_info[:-1], fp) break continue # for displaying learned policies, not learning if self.display: time.sleep(0.1) self.env.render() continue # learn, update all policies in trainers, if not in display or benchmark mode loss = None for agent in self.trainers: agent.preupdate() for agent in self.trainers: loss = agent.update(self.trainers, train_step) if loss is not None: logging.debug(f"{agent}'s loss is {loss}") ############################################################################## # save model # display training output ############################################################################## if terminal and (len(episode_rewards) % self.save_rate == 0): # save the model separately if self.save_trainers: for _ in self.trainers: U.save_as_scope(_.name, save_dir=self.save_dir, model_name=self.model_name) # save all model paramters U.save_state(self.save_dir + self.model_name, saver=saver) if num_adversaries == 0: logging.info(f"steps: {train_step}, episodes: {len(episode_rewards)}, " f"mean episode reward: {np.mean(episode_rewards[-self.save_rate:])}, " f"time: {round(time.time() - t_start, 3)}") t_start = time.time() final_ep_rewards.append(np.mean(episode_rewards[-self.save_rate:])) for rew in agent_rewards: final_ep_ag_rewards.append(np.mean(rew[-self.save_rate:])) ############################################################################## # saves final episode reward for plotting training curve ############################################################################## if len(episode_rewards) > self.num_episodes: module_path = os.getcwd() rew_file_name = self.plots_dir + self.exp_name + "_rewards.pkl" rew_file_name = os.path.join(module_path, rew_file_name) with open(rew_file_name, 'wb') as fp: pickle.dump(final_ep_rewards, fp) agrew_file_name = self.plots_dir + self.exp_name + '_agrewards.pkl' with open(agrew_file_name, 'wb') as fp: pickle.dump(final_ep_ag_rewards, fp) logging.info(f'...Finished total of {len(episode_rewards)} episodes') break def predict(self, obs_n, train=True): if train: action_n = [agent.action(obs) for agent, obs in zip(self.trainers, obs_n)] return action_n else: with U.single_threaded_session(): U.initialize() if self.load_dir == '': self.load_dir = self.save_dir logging.info("loading model...") try: saver = tf.train.import_meta_graph(self.save_dir + self.model_name + ".meta") U.load_state(tf.train.latest_checkpoint(self.save_dir), saver=saver) action_n = [agent.action(obs) for agent, obs in zip(self.trainers, obs_n)] return action_n except IOError as e: logging.error(f"Loading model error when not Train, please check path: " f"{self.save_dir + self.model_name} whether model is exist.") logging.error(str(e)) logging.error("Please change the path of model or retrain the model, " "retrain model: set the hyperparamter TRAIN as True in drl_negotiation/hyperparamters.py!") sys.exit()
[ "argparse.Namespace", "pickle.dump", "drl_negotiation.utils.get_trainers", "drl_negotiation.utils.save_as_scope", "numpy.clip", "drl_negotiation.utils.get_saver", "numpy.mean", "drl_negotiation.utils.save_state", "os.path.join", "logging.error", "tensorflow.compat.v1.train.import_meta_graph", ...
[((3340, 3367), 'drl_negotiation.utils.single_threaded_session', 'U.single_threaded_session', ([], {}), '()\n', (3365, 3367), True, 'import drl_negotiation.utils as U\n'), ((3836, 4098), 'argparse.Namespace', 'argparse.Namespace', ([], {}), "(**{'good_policy': self.good_policy, 'adv_policy': self.\n adv_policy, 'lr': self.lr, 'num_units': self.num_units, 'batch_size':\n self.batch_size, 'max_episode_len': self.max_episode_len, 'gamma': self\n .gamma, 'n_steps': self.n_steps})\n", (3854, 4098), False, 'import argparse\n'), ((4466, 4529), 'drl_negotiation.utils.get_trainers', 'U.get_trainers', (['self.env', 'num_adversaries', 'obs_shape_n', 'arglist'], {}), '(self.env, num_adversaries, obs_shape_n, arglist)\n', (4480, 4529), True, 'import drl_negotiation.utils as U\n'), ((4542, 4633), 'logging.info', 'logging.info', (['f"""Using good policy {self.good_policy} and adv policy {self.adv_policy}"""'], {}), "(\n f'Using good policy {self.good_policy} and adv policy {self.adv_policy}')\n", (4554, 4633), False, 'import logging\n'), ((5321, 5348), 'drl_negotiation.utils.single_threaded_session', 'U.single_threaded_session', ([], {}), '()\n', (5346, 5348), True, 'import drl_negotiation.utils as U\n'), ((5817, 6079), 'argparse.Namespace', 'argparse.Namespace', ([], {}), "(**{'good_policy': self.good_policy, 'adv_policy': self.\n adv_policy, 'lr': self.lr, 'num_units': self.num_units, 'batch_size':\n self.batch_size, 'max_episode_len': self.max_episode_len, 'gamma': self\n .gamma, 'n_steps': self.n_steps})\n", (5835, 6079), False, 'import argparse\n'), ((6279, 6342), 'drl_negotiation.utils.get_trainers', 'U.get_trainers', (['self.env', 'num_adversaries', 'obs_shape_n', 'arglist'], {}), '(self.env, num_adversaries, obs_shape_n, arglist)\n', (6293, 6342), True, 'import drl_negotiation.utils as U\n'), ((6355, 6446), 'logging.info', 'logging.info', (['f"""Using good policy {self.good_policy} and adv policy {self.adv_policy}"""'], {}), "(\n f'Using good policy {self.good_policy} and adv policy {self.adv_policy}')\n", (6367, 6446), False, 'import logging\n'), ((6455, 6469), 'drl_negotiation.utils.initialize', 'U.initialize', ([], {}), '()\n', (6467, 6469), True, 'import drl_negotiation.utils as U\n'), ((6573, 6589), 'tensorflow.compat.v1.train.Saver', 'tf.train.Saver', ([], {}), '()\n', (6587, 6589), True, 'import tensorflow.compat.v1 as tf\n'), ((7308, 7319), 'time.time', 'time.time', ([], {}), '()\n', (7317, 7319), False, 'import time\n'), ((7339, 7368), 'tqdm.tqdm', 'tqdm', ([], {'total': 'self.num_episodes'}), '(total=self.num_episodes)\n', (7343, 7368), False, 'from tqdm import tqdm\n'), ((6669, 6710), 'logging.info', 'logging.info', (['"""Loading previous state..."""'], {}), "('Loading previous state...')\n", (6681, 6710), False, 'import logging\n'), ((6942, 6955), 'drl_negotiation.utils.get_saver', 'U.get_saver', ([], {}), '()\n', (6953, 6955), True, 'import drl_negotiation.utils as U\n'), ((12663, 12690), 'drl_negotiation.utils.single_threaded_session', 'U.single_threaded_session', ([], {}), '()\n', (12688, 12690), True, 'import drl_negotiation.utils as U\n'), ((12708, 12722), 'drl_negotiation.utils.initialize', 'U.initialize', ([], {}), '()\n', (12720, 12722), True, 'import drl_negotiation.utils as U\n'), ((12830, 12862), 'logging.info', 'logging.info', (['"""loading model..."""'], {}), "('loading model...')\n", (12842, 12862), False, 'import logging\n'), ((6831, 6872), 'tensorflow.compat.v1.train.latest_checkpoint', 'tf.train.latest_checkpoint', (['self.load_dir'], {}), '(self.load_dir)\n', (6857, 6872), True, 'import tensorflow.compat.v1 as tf\n'), ((9691, 9706), 'time.sleep', 'time.sleep', (['(0.1)'], {}), '(0.1)\n', (9701, 9706), False, 'import time\n'), ((10848, 10906), 'drl_negotiation.utils.save_state', 'U.save_state', (['(self.save_dir + self.model_name)'], {'saver': 'saver'}), '(self.save_dir + self.model_name, saver=saver)\n', (10860, 10906), True, 'import drl_negotiation.utils as U\n'), ((11254, 11265), 'time.time', 'time.time', ([], {}), '()\n', (11263, 11265), False, 'import time\n'), ((11842, 11853), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (11851, 11853), False, 'import os, sys\n'), ((11974, 12014), 'os.path.join', 'os.path.join', (['module_path', 'rew_file_name'], {}), '(module_path, rew_file_name)\n', (11986, 12014), False, 'import os, sys\n'), ((12912, 12981), 'tensorflow.compat.v1.train.import_meta_graph', 'tf.train.import_meta_graph', (["(self.save_dir + self.model_name + '.meta')"], {}), "(self.save_dir + self.model_name + '.meta')\n", (12938, 12981), True, 'import tensorflow.compat.v1 as tf\n'), ((7736, 7822), 'numpy.clip', 'np.clip', (['action_n[i]', 'self.env.action_space[i].low', 'self.env.action_space[i].high'], {}), '(action_n[i], self.env.action_space[i].low, self.env.action_space[i]\n .high)\n', (7743, 7822), True, 'import numpy as np\n'), ((9341, 9394), 'logging.info', 'logging.info', (['"""Finished benchmarking, now saving...."""'], {}), "('Finished benchmarking, now saving....')\n", (9353, 9394), False, 'import logging\n'), ((10155, 10197), 'logging.debug', 'logging.debug', (['f"""{agent}\'s loss is {loss}"""'], {}), '(f"{agent}\'s loss is {loss}")\n', (10168, 10197), False, 'import logging\n'), ((11310, 11352), 'numpy.mean', 'np.mean', (['episode_rewards[-self.save_rate:]'], {}), '(episode_rewards[-self.save_rate:])\n', (11317, 11352), True, 'import numpy as np\n'), ((12097, 12130), 'pickle.dump', 'pickle.dump', (['final_ep_rewards', 'fp'], {}), '(final_ep_rewards, fp)\n', (12108, 12130), False, 'import pickle\n'), ((12303, 12339), 'pickle.dump', 'pickle.dump', (['final_ep_ag_rewards', 'fp'], {}), '(final_ep_ag_rewards, fp)\n', (12314, 12339), False, 'import pickle\n'), ((13015, 13056), 'tensorflow.compat.v1.train.latest_checkpoint', 'tf.train.latest_checkpoint', (['self.save_dir'], {}), '(self.save_dir)\n', (13041, 13056), True, 'import tensorflow.compat.v1 as tf\n'), ((13260, 13400), 'logging.error', 'logging.error', (['f"""Loading model error when not Train, please check path: {self.save_dir + self.model_name} whether model is exist."""'], {}), "(\n f'Loading model error when not Train, please check path: {self.save_dir + self.model_name} whether model is exist.'\n )\n", (13273, 13400), False, 'import logging\n'), ((13491, 13660), 'logging.error', 'logging.error', (['"""Please change the path of model or retrain the model, retrain model: set the hyperparamter TRAIN as True in drl_negotiation/hyperparamters.py!"""'], {}), "(\n 'Please change the path of model or retrain the model, retrain model: set the hyperparamter TRAIN as True in drl_negotiation/hyperparamters.py!'\n )\n", (13504, 13660), False, 'import logging\n'), ((13708, 13718), 'sys.exit', 'sys.exit', ([], {}), '()\n', (13716, 13718), False, 'import os, sys\n'), ((9481, 9513), 'pickle.dump', 'pickle.dump', (['agent_info[:-1]', 'fp'], {}), '(agent_info[:-1], fp)\n', (9492, 9513), False, 'import pickle\n'), ((10705, 10780), 'drl_negotiation.utils.save_as_scope', 'U.save_as_scope', (['_.name'], {'save_dir': 'self.save_dir', 'model_name': 'self.model_name'}), '(_.name, save_dir=self.save_dir, model_name=self.model_name)\n', (10720, 10780), True, 'import drl_negotiation.utils as U\n'), ((11451, 11481), 'numpy.mean', 'np.mean', (['rew[-self.save_rate:]'], {}), '(rew[-self.save_rate:])\n', (11458, 11481), True, 'import numpy as np\n'), ((11103, 11145), 'numpy.mean', 'np.mean', (['episode_rewards[-self.save_rate:]'], {}), '(episode_rewards[-self.save_rate:])\n', (11110, 11145), True, 'import numpy as np\n'), ((11195, 11206), 'time.time', 'time.time', ([], {}), '()\n', (11204, 11206), False, 'import time\n')]
from atomicplot.data import XYDataObject import unittest import numpy as np class DataObjectTest(unittest.TestCase): def test_inputtype(self): with self.assertRaises(TypeError): x = 'test_string' y = [1, 2, 3, 4] XYDataObject(x, y) with self.assertRaises(ValueError): x = [1, 2, 3, 4, 5] y = [1, 2, 3, 4] XYDataObject(x, y) with self.assertRaises(ValueError): x = np.arange(10).reshape(5) y = np.arange(5) XYDataObject(x, y) def test_add(self): x = np.arange(4) y = np.arange(4) + 5 d = XYDataObject(x, y) d_out = d + 10 # Test adding scalar self.assertTrue(np.array_equal(d.y + 10, d_out.y)) d_out = d + y[::-1] # Test adding array self.assertTrue(np.array_equal(d.y + y[::-1], d_out.y)) d_out = d + XYDataObject(x, y ** 2) # Test subtracting another DataObject self.assertTrue(np.array_equal(d.y + y**2, d_out.y)) def test_sub(self): x = np.arange(4) y = np.arange(4) + 5 d = XYDataObject(x, y) d_out = d - 10 # Test subtracting scalar self.assertTrue(np.array_equal(d.y - 10, d_out.y)) d_out = d - y[::-1] # Test subtracting array self.assertTrue(np.array_equal(d.y - y[::-1], d_out.y)) d_out = d - XYDataObject(x, y ** 2) # Test adding another DataObject self.assertTrue(np.array_equal(d.y - y**2, d_out.y)) def test_mul(self): x = np.arange(4) y = np.arange(4) + 5 d = XYDataObject(x, y) d_out = d * 10 # Test multiplying scalar self.assertTrue(np.array_equal(d.y * 10, d_out.y)) d_out = d * y[::-1] # Test multiplying array self.assertTrue(np.array_equal(d.y * y[::-1], d_out.y)) d_out = d * XYDataObject(x, y ** 2) # Test multiplying another DataObject self.assertTrue(np.array_equal(d.y * y**2, d_out.y)) def test_truediv(self): x = np.arange(4) y = np.arange(4) + 5 d = XYDataObject(x, y) d_out = d / 10 self.assertTrue(np.array_equal(d.y / 10, d_out.y)) d_out = d / y[::-1] self.assertTrue(np.array_equal(d.y / y[::-1], d_out.y)) d_out = d / XYDataObject(x, y ** 2) self.assertTrue(np.array_equal(d.y / y**2, d_out.y)) def test_floordiv(self): x = np.arange(4) y = np.arange(4) + 5 d = XYDataObject(x, y) d_out = d // 10 self.assertTrue(np.array_equal(d.y // 10, d_out.y)) d_out = d // y[::-1] self.assertTrue(np.array_equal(d.y // y[::-1], d_out.y)) d_out = d // XYDataObject(x, y ** 2) self.assertTrue(np.array_equal(d.y // y**2, d_out.y)) def test_pow(self): x = np.arange(4) y = np.arange(4) + 5 d = XYDataObject(x, y) d_out = d ** 10 # Test multiplying scalar self.assertTrue(np.array_equal(d.y ** 10, d_out.y)) d_out = d ** y[::-1] # Test multiplying array self.assertTrue(np.array_equal(d.y ** y[::-1], d_out.y)) d_out = d ** XYDataObject(x, y ** 2) # Test multiplying another DataObject self.assertTrue(np.array_equal(d.y ** (y**2), d_out.y)) def test_neg(self): x = np.arange(4) y = np.arange(4) + 5 d = XYDataObject(x, y) d_out = -d self.assertTrue(np.array_equal(-1*d.y, d_out.y)) def test_abs(self): x = np.arange(4) y = np.arange(4) - 3 d = XYDataObject(x, y) d_out = abs(d) self.assertTrue(np.array_equal(np.absolute(d.y), d_out.y)) def test_isub(self): x = np.arange(4) y = (np.arange(4) + 5) d = XYDataObject(x, y) d -= 3 self.assertTrue(np.array_equal(d.y, y - 3)) def test_iadd(self): x = np.arange(4) y = (np.arange(4) + 5) d = XYDataObject(x, y) d += 3 self.assertTrue(np.array_equal(d.y, y + 3)) def test_imul(self): x = np.arange(4) y = (np.arange(4) + 5) d = XYDataObject(x, y) d *= 3 self.assertTrue(np.array_equal(d.y, y * 3)) def test_itruediv(self): x = np.arange(4) y = (np.arange(4) + 5).astype('float') d = XYDataObject(x, y) d /= 3 self.assertTrue(np.array_equal(d.y, y/3)) def test_ifloordiv(self): x = np.arange(4) y = (np.arange(4) + 5).astype('float') d = XYDataObject(x, y) d //= 3 self.assertTrue(np.array_equal(d.y, y // 3)) def test_ipow(self): x = np.arange(4) y = (np.arange(4) + 5) d = XYDataObject(x, y) d **= 3 self.assertTrue(np.array_equal(d.y, y**3)) if __name__ == '__main__': unittest.main()
[ "unittest.main", "numpy.absolute", "numpy.arange", "numpy.array_equal", "atomicplot.data.XYDataObject" ]
[((5009, 5024), 'unittest.main', 'unittest.main', ([], {}), '()\n', (5022, 5024), False, 'import unittest\n'), ((625, 637), 'numpy.arange', 'np.arange', (['(4)'], {}), '(4)\n', (634, 637), True, 'import numpy as np\n'), ((681, 699), 'atomicplot.data.XYDataObject', 'XYDataObject', (['x', 'y'], {}), '(x, y)\n', (693, 699), False, 'from atomicplot.data import XYDataObject\n'), ((1113, 1125), 'numpy.arange', 'np.arange', (['(4)'], {}), '(4)\n', (1122, 1125), True, 'import numpy as np\n'), ((1169, 1187), 'atomicplot.data.XYDataObject', 'XYDataObject', (['x', 'y'], {}), '(x, y)\n', (1181, 1187), False, 'from atomicplot.data import XYDataObject\n'), ((1606, 1618), 'numpy.arange', 'np.arange', (['(4)'], {}), '(4)\n', (1615, 1618), True, 'import numpy as np\n'), ((1662, 1680), 'atomicplot.data.XYDataObject', 'XYDataObject', (['x', 'y'], {}), '(x, y)\n', (1674, 1680), False, 'from atomicplot.data import XYDataObject\n'), ((2108, 2120), 'numpy.arange', 'np.arange', (['(4)'], {}), '(4)\n', (2117, 2120), True, 'import numpy as np\n'), ((2164, 2182), 'atomicplot.data.XYDataObject', 'XYDataObject', (['x', 'y'], {}), '(x, y)\n', (2176, 2182), False, 'from atomicplot.data import XYDataObject\n'), ((2519, 2531), 'numpy.arange', 'np.arange', (['(4)'], {}), '(4)\n', (2528, 2531), True, 'import numpy as np\n'), ((2575, 2593), 'atomicplot.data.XYDataObject', 'XYDataObject', (['x', 'y'], {}), '(x, y)\n', (2587, 2593), False, 'from atomicplot.data import XYDataObject\n'), ((2931, 2943), 'numpy.arange', 'np.arange', (['(4)'], {}), '(4)\n', (2940, 2943), True, 'import numpy as np\n'), ((2987, 3005), 'atomicplot.data.XYDataObject', 'XYDataObject', (['x', 'y'], {}), '(x, y)\n', (2999, 3005), False, 'from atomicplot.data import XYDataObject\n'), ((3437, 3449), 'numpy.arange', 'np.arange', (['(4)'], {}), '(4)\n', (3446, 3449), True, 'import numpy as np\n'), ((3493, 3511), 'atomicplot.data.XYDataObject', 'XYDataObject', (['x', 'y'], {}), '(x, y)\n', (3505, 3511), False, 'from atomicplot.data import XYDataObject\n'), ((3630, 3642), 'numpy.arange', 'np.arange', (['(4)'], {}), '(4)\n', (3639, 3642), True, 'import numpy as np\n'), ((3686, 3704), 'atomicplot.data.XYDataObject', 'XYDataObject', (['x', 'y'], {}), '(x, y)\n', (3698, 3704), False, 'from atomicplot.data import XYDataObject\n'), ((3838, 3850), 'numpy.arange', 'np.arange', (['(4)'], {}), '(4)\n', (3847, 3850), True, 'import numpy as np\n'), ((3896, 3914), 'atomicplot.data.XYDataObject', 'XYDataObject', (['x', 'y'], {}), '(x, y)\n', (3908, 3914), False, 'from atomicplot.data import XYDataObject\n'), ((4027, 4039), 'numpy.arange', 'np.arange', (['(4)'], {}), '(4)\n', (4036, 4039), True, 'import numpy as np\n'), ((4085, 4103), 'atomicplot.data.XYDataObject', 'XYDataObject', (['x', 'y'], {}), '(x, y)\n', (4097, 4103), False, 'from atomicplot.data import XYDataObject\n'), ((4216, 4228), 'numpy.arange', 'np.arange', (['(4)'], {}), '(4)\n', (4225, 4228), True, 'import numpy as np\n'), ((4274, 4292), 'atomicplot.data.XYDataObject', 'XYDataObject', (['x', 'y'], {}), '(x, y)\n', (4286, 4292), False, 'from atomicplot.data import XYDataObject\n'), ((4409, 4421), 'numpy.arange', 'np.arange', (['(4)'], {}), '(4)\n', (4418, 4421), True, 'import numpy as np\n'), ((4483, 4501), 'atomicplot.data.XYDataObject', 'XYDataObject', (['x', 'y'], {}), '(x, y)\n', (4495, 4501), False, 'from atomicplot.data import XYDataObject\n'), ((4617, 4629), 'numpy.arange', 'np.arange', (['(4)'], {}), '(4)\n', (4626, 4629), True, 'import numpy as np\n'), ((4691, 4709), 'atomicplot.data.XYDataObject', 'XYDataObject', (['x', 'y'], {}), '(x, y)\n', (4703, 4709), False, 'from atomicplot.data import XYDataObject\n'), ((4824, 4836), 'numpy.arange', 'np.arange', (['(4)'], {}), '(4)\n', (4833, 4836), True, 'import numpy as np\n'), ((4882, 4900), 'atomicplot.data.XYDataObject', 'XYDataObject', (['x', 'y'], {}), '(x, y)\n', (4894, 4900), False, 'from atomicplot.data import XYDataObject\n'), ((273, 291), 'atomicplot.data.XYDataObject', 'XYDataObject', (['x', 'y'], {}), '(x, y)\n', (285, 291), False, 'from atomicplot.data import XYDataObject\n'), ((415, 433), 'atomicplot.data.XYDataObject', 'XYDataObject', (['x', 'y'], {}), '(x, y)\n', (427, 433), False, 'from atomicplot.data import XYDataObject\n'), ((540, 552), 'numpy.arange', 'np.arange', (['(5)'], {}), '(5)\n', (549, 552), True, 'import numpy as np\n'), ((566, 584), 'atomicplot.data.XYDataObject', 'XYDataObject', (['x', 'y'], {}), '(x, y)\n', (578, 584), False, 'from atomicplot.data import XYDataObject\n'), ((651, 663), 'numpy.arange', 'np.arange', (['(4)'], {}), '(4)\n', (660, 663), True, 'import numpy as np\n'), ((773, 806), 'numpy.array_equal', 'np.array_equal', (['(d.y + 10)', 'd_out.y'], {}), '(d.y + 10, d_out.y)\n', (787, 806), True, 'import numpy as np\n'), ((885, 923), 'numpy.array_equal', 'np.array_equal', (['(d.y + y[::-1])', 'd_out.y'], {}), '(d.y + y[::-1], d_out.y)\n', (899, 923), True, 'import numpy as np\n'), ((948, 971), 'atomicplot.data.XYDataObject', 'XYDataObject', (['x', '(y ** 2)'], {}), '(x, y ** 2)\n', (960, 971), False, 'from atomicplot.data import XYDataObject\n'), ((1036, 1073), 'numpy.array_equal', 'np.array_equal', (['(d.y + y ** 2)', 'd_out.y'], {}), '(d.y + y ** 2, d_out.y)\n', (1050, 1073), True, 'import numpy as np\n'), ((1139, 1151), 'numpy.arange', 'np.arange', (['(4)'], {}), '(4)\n', (1148, 1151), True, 'import numpy as np\n'), ((1266, 1299), 'numpy.array_equal', 'np.array_equal', (['(d.y - 10)', 'd_out.y'], {}), '(d.y - 10, d_out.y)\n', (1280, 1299), True, 'import numpy as np\n'), ((1383, 1421), 'numpy.array_equal', 'np.array_equal', (['(d.y - y[::-1])', 'd_out.y'], {}), '(d.y - y[::-1], d_out.y)\n', (1397, 1421), True, 'import numpy as np\n'), ((1446, 1469), 'atomicplot.data.XYDataObject', 'XYDataObject', (['x', '(y ** 2)'], {}), '(x, y ** 2)\n', (1458, 1469), False, 'from atomicplot.data import XYDataObject\n'), ((1529, 1566), 'numpy.array_equal', 'np.array_equal', (['(d.y - y ** 2)', 'd_out.y'], {}), '(d.y - y ** 2, d_out.y)\n', (1543, 1566), True, 'import numpy as np\n'), ((1632, 1644), 'numpy.arange', 'np.arange', (['(4)'], {}), '(4)\n', (1641, 1644), True, 'import numpy as np\n'), ((1759, 1792), 'numpy.array_equal', 'np.array_equal', (['(d.y * 10)', 'd_out.y'], {}), '(d.y * 10, d_out.y)\n', (1773, 1792), True, 'import numpy as np\n'), ((1876, 1914), 'numpy.array_equal', 'np.array_equal', (['(d.y * y[::-1])', 'd_out.y'], {}), '(d.y * y[::-1], d_out.y)\n', (1890, 1914), True, 'import numpy as np\n'), ((1939, 1962), 'atomicplot.data.XYDataObject', 'XYDataObject', (['x', '(y ** 2)'], {}), '(x, y ** 2)\n', (1951, 1962), False, 'from atomicplot.data import XYDataObject\n'), ((2027, 2064), 'numpy.array_equal', 'np.array_equal', (['(d.y * y ** 2)', 'd_out.y'], {}), '(d.y * y ** 2, d_out.y)\n', (2041, 2064), True, 'import numpy as np\n'), ((2134, 2146), 'numpy.arange', 'np.arange', (['(4)'], {}), '(4)\n', (2143, 2146), True, 'import numpy as np\n'), ((2234, 2267), 'numpy.array_equal', 'np.array_equal', (['(d.y / 10)', 'd_out.y'], {}), '(d.y / 10, d_out.y)\n', (2248, 2267), True, 'import numpy as np\n'), ((2325, 2363), 'numpy.array_equal', 'np.array_equal', (['(d.y / y[::-1])', 'd_out.y'], {}), '(d.y / y[::-1], d_out.y)\n', (2339, 2363), True, 'import numpy as np\n'), ((2388, 2411), 'atomicplot.data.XYDataObject', 'XYDataObject', (['x', '(y ** 2)'], {}), '(x, y ** 2)\n', (2400, 2411), False, 'from atomicplot.data import XYDataObject\n'), ((2437, 2474), 'numpy.array_equal', 'np.array_equal', (['(d.y / y ** 2)', 'd_out.y'], {}), '(d.y / y ** 2, d_out.y)\n', (2451, 2474), True, 'import numpy as np\n'), ((2545, 2557), 'numpy.arange', 'np.arange', (['(4)'], {}), '(4)\n', (2554, 2557), True, 'import numpy as np\n'), ((2646, 2680), 'numpy.array_equal', 'np.array_equal', (['(d.y // 10)', 'd_out.y'], {}), '(d.y // 10, d_out.y)\n', (2660, 2680), True, 'import numpy as np\n'), ((2739, 2778), 'numpy.array_equal', 'np.array_equal', (['(d.y // y[::-1])', 'd_out.y'], {}), '(d.y // y[::-1], d_out.y)\n', (2753, 2778), True, 'import numpy as np\n'), ((2804, 2827), 'atomicplot.data.XYDataObject', 'XYDataObject', (['x', '(y ** 2)'], {}), '(x, y ** 2)\n', (2816, 2827), False, 'from atomicplot.data import XYDataObject\n'), ((2853, 2891), 'numpy.array_equal', 'np.array_equal', (['(d.y // y ** 2)', 'd_out.y'], {}), '(d.y // y ** 2, d_out.y)\n', (2867, 2891), True, 'import numpy as np\n'), ((2957, 2969), 'numpy.arange', 'np.arange', (['(4)'], {}), '(4)\n', (2966, 2969), True, 'import numpy as np\n'), ((3085, 3119), 'numpy.array_equal', 'np.array_equal', (['(d.y ** 10)', 'd_out.y'], {}), '(d.y ** 10, d_out.y)\n', (3099, 3119), True, 'import numpy as np\n'), ((3204, 3243), 'numpy.array_equal', 'np.array_equal', (['(d.y ** y[::-1])', 'd_out.y'], {}), '(d.y ** y[::-1], d_out.y)\n', (3218, 3243), True, 'import numpy as np\n'), ((3269, 3292), 'atomicplot.data.XYDataObject', 'XYDataObject', (['x', '(y ** 2)'], {}), '(x, y ** 2)\n', (3281, 3292), False, 'from atomicplot.data import XYDataObject\n'), ((3357, 3395), 'numpy.array_equal', 'np.array_equal', (['(d.y ** y ** 2)', 'd_out.y'], {}), '(d.y ** y ** 2, d_out.y)\n', (3371, 3395), True, 'import numpy as np\n'), ((3463, 3475), 'numpy.arange', 'np.arange', (['(4)'], {}), '(4)\n', (3472, 3475), True, 'import numpy as np\n'), ((3557, 3590), 'numpy.array_equal', 'np.array_equal', (['(-1 * d.y)', 'd_out.y'], {}), '(-1 * d.y, d_out.y)\n', (3571, 3590), True, 'import numpy as np\n'), ((3656, 3668), 'numpy.arange', 'np.arange', (['(4)'], {}), '(4)\n', (3665, 3668), True, 'import numpy as np\n'), ((3865, 3877), 'numpy.arange', 'np.arange', (['(4)'], {}), '(4)\n', (3874, 3877), True, 'import numpy as np\n'), ((3958, 3984), 'numpy.array_equal', 'np.array_equal', (['d.y', '(y - 3)'], {}), '(d.y, y - 3)\n', (3972, 3984), True, 'import numpy as np\n'), ((4054, 4066), 'numpy.arange', 'np.arange', (['(4)'], {}), '(4)\n', (4063, 4066), True, 'import numpy as np\n'), ((4147, 4173), 'numpy.array_equal', 'np.array_equal', (['d.y', '(y + 3)'], {}), '(d.y, y + 3)\n', (4161, 4173), True, 'import numpy as np\n'), ((4243, 4255), 'numpy.arange', 'np.arange', (['(4)'], {}), '(4)\n', (4252, 4255), True, 'import numpy as np\n'), ((4336, 4362), 'numpy.array_equal', 'np.array_equal', (['d.y', '(y * 3)'], {}), '(d.y, y * 3)\n', (4350, 4362), True, 'import numpy as np\n'), ((4545, 4571), 'numpy.array_equal', 'np.array_equal', (['d.y', '(y / 3)'], {}), '(d.y, y / 3)\n', (4559, 4571), True, 'import numpy as np\n'), ((4754, 4781), 'numpy.array_equal', 'np.array_equal', (['d.y', '(y // 3)'], {}), '(d.y, y // 3)\n', (4768, 4781), True, 'import numpy as np\n'), ((4851, 4863), 'numpy.arange', 'np.arange', (['(4)'], {}), '(4)\n', (4860, 4863), True, 'import numpy as np\n'), ((4945, 4972), 'numpy.array_equal', 'np.array_equal', (['d.y', '(y ** 3)'], {}), '(d.y, y ** 3)\n', (4959, 4972), True, 'import numpy as np\n'), ((3769, 3785), 'numpy.absolute', 'np.absolute', (['d.y'], {}), '(d.y)\n', (3780, 3785), True, 'import numpy as np\n'), ((498, 511), 'numpy.arange', 'np.arange', (['(10)'], {}), '(10)\n', (507, 511), True, 'import numpy as np\n'), ((4436, 4448), 'numpy.arange', 'np.arange', (['(4)'], {}), '(4)\n', (4445, 4448), True, 'import numpy as np\n'), ((4644, 4656), 'numpy.arange', 'np.arange', (['(4)'], {}), '(4)\n', (4653, 4656), True, 'import numpy as np\n')]
import numpy as np import pytest from nengo.builder import Signal from nengo.builder.operator import SparseDotInc from nengo.exceptions import BuildError def test_sparsedotinc_builderror(): A = Signal(np.ones(2)) X = Signal(np.ones(2)) Y = Signal(np.ones(2)) with pytest.raises(BuildError, match="must be a sparse Signal"): SparseDotInc(A, X, Y)
[ "pytest.raises", "numpy.ones", "nengo.builder.operator.SparseDotInc" ]
[((208, 218), 'numpy.ones', 'np.ones', (['(2)'], {}), '(2)\n', (215, 218), True, 'import numpy as np\n'), ((235, 245), 'numpy.ones', 'np.ones', (['(2)'], {}), '(2)\n', (242, 245), True, 'import numpy as np\n'), ((262, 272), 'numpy.ones', 'np.ones', (['(2)'], {}), '(2)\n', (269, 272), True, 'import numpy as np\n'), ((284, 342), 'pytest.raises', 'pytest.raises', (['BuildError'], {'match': '"""must be a sparse Signal"""'}), "(BuildError, match='must be a sparse Signal')\n", (297, 342), False, 'import pytest\n'), ((352, 373), 'nengo.builder.operator.SparseDotInc', 'SparseDotInc', (['A', 'X', 'Y'], {}), '(A, X, Y)\n', (364, 373), False, 'from nengo.builder.operator import SparseDotInc\n')]
import cv2 as cv from bbox import BoundingBox from opticalFlow import OpticalFlowTracker from utils import displayImage, drawBbox, drawVectfromBbox, opticalFlow, euclidianDistance import numpy as np class Trackers(OpticalFlowTracker): def __init__(self,bboxes): self.positions = [box.center for box in bboxes] self.bboxes = bboxes def B_hats_next(self,dVects): bboxes_next = [] for bbox,dvect in zip(self.bboxes,dVects): bboxes_next.append(self.B_hat_next(bbox,dvect)) return bboxes_next def dVects(self,frame1,frame2,multipliers = [],blur=False): if len(multipliers)==0: multipliers=np.ones_like(self.bboxes) flow = self.opticalFlowChart(frame1,frame2,blur=blur) dVects = [] for bbox,mult in zip(self.bboxes,multipliers): dVect = self.dVector(bbox,flow,d_method="Average",multiplier=mult) #May add different d-vector calculation methods dVects.append(dVect) return dVects def predict(self,frame1,frame2,multipliers = []): dVects = self.dVects(frame1,frame2,multipliers) b_hats_next = self.B_hats_next(dVects) return b_hats_next def drawBBoxes(self,bboxes,frame): for bbox in bboxes: frame = drawBbox(frame,bbox) return frame if (__name__ == '__main__'): img1 = "img0370.jpg" img2 = "img0371.jpg" img3 = "img0372.jpg" img4 = "img0373.jpg" img5 = "img0374.jpg" bbox0 = BoundingBox(x0 = 980,x1 = 1026,y0 = 300,y1 = 360) bbox1 = BoundingBox(x0 = 513, x1 = 560, y0 = 315, y1 = 355) bbox2 = BoundingBox(x0 = 790, x1 = 805, y0= 130,y1 = 145) bbox3 = BoundingBox(x0 = 618, x1 = 638, y0= 625,y1 = 640) framet1 = cv.imread(img1) framet2 = cv.imread(img2) framet3 = cv.imread(img3) framet4 = cv.imread(img4) framet5 = cv.imread(img5) mult1 = bbox0.area//100 mult2 = bbox1.area//100 mult3 = bbox2.area//100 mult4 = bbox2.area//100 mults = [mult1,mult2,mult3,mult4] print(len(mults)) bboxes = [bbox0,bbox1,bbox2,bbox3] trackers = Trackers(bboxes) predictions1 = trackers.predict(framet1,framet2,multipliers=mults) trackers.bboxes=predictions1 predictions2 = trackers.predict(framet2,framet3,multipliers=mults) trackers.bboxes = predictions2 predictions3 = trackers.predict(framet3,framet4,multipliers=mults) trackers.bboxes = predictions3 predictions4 = trackers.predict(framet4,framet5,multipliers=mults) framet = trackers.drawBBoxes(predictions1,framet1) framet = trackers.drawBBoxes(predictions2,framet1) framet = trackers.drawBBoxes(predictions3,framet1) framet = trackers.drawBBoxes(predictions4,framet1) displayImage(framet)
[ "utils.displayImage", "numpy.ones_like", "utils.drawBbox", "cv2.imread", "bbox.BoundingBox" ]
[((1526, 1570), 'bbox.BoundingBox', 'BoundingBox', ([], {'x0': '(980)', 'x1': '(1026)', 'y0': '(300)', 'y1': '(360)'}), '(x0=980, x1=1026, y0=300, y1=360)\n', (1537, 1570), False, 'from bbox import BoundingBox\n'), ((1588, 1631), 'bbox.BoundingBox', 'BoundingBox', ([], {'x0': '(513)', 'x1': '(560)', 'y0': '(315)', 'y1': '(355)'}), '(x0=513, x1=560, y0=315, y1=355)\n', (1599, 1631), False, 'from bbox import BoundingBox\n'), ((1652, 1695), 'bbox.BoundingBox', 'BoundingBox', ([], {'x0': '(790)', 'x1': '(805)', 'y0': '(130)', 'y1': '(145)'}), '(x0=790, x1=805, y0=130, y1=145)\n', (1663, 1695), False, 'from bbox import BoundingBox\n'), ((1714, 1757), 'bbox.BoundingBox', 'BoundingBox', ([], {'x0': '(618)', 'x1': '(638)', 'y0': '(625)', 'y1': '(640)'}), '(x0=618, x1=638, y0=625, y1=640)\n', (1725, 1757), False, 'from bbox import BoundingBox\n'), ((1779, 1794), 'cv2.imread', 'cv.imread', (['img1'], {}), '(img1)\n', (1788, 1794), True, 'import cv2 as cv\n'), ((1809, 1824), 'cv2.imread', 'cv.imread', (['img2'], {}), '(img2)\n', (1818, 1824), True, 'import cv2 as cv\n'), ((1839, 1854), 'cv2.imread', 'cv.imread', (['img3'], {}), '(img3)\n', (1848, 1854), True, 'import cv2 as cv\n'), ((1869, 1884), 'cv2.imread', 'cv.imread', (['img4'], {}), '(img4)\n', (1878, 1884), True, 'import cv2 as cv\n'), ((1899, 1914), 'cv2.imread', 'cv.imread', (['img5'], {}), '(img5)\n', (1908, 1914), True, 'import cv2 as cv\n'), ((2776, 2796), 'utils.displayImage', 'displayImage', (['framet'], {}), '(framet)\n', (2788, 2796), False, 'from utils import displayImage, drawBbox, drawVectfromBbox, opticalFlow, euclidianDistance\n'), ((676, 701), 'numpy.ones_like', 'np.ones_like', (['self.bboxes'], {}), '(self.bboxes)\n', (688, 701), True, 'import numpy as np\n'), ((1311, 1332), 'utils.drawBbox', 'drawBbox', (['frame', 'bbox'], {}), '(frame, bbox)\n', (1319, 1332), False, 'from utils import displayImage, drawBbox, drawVectfromBbox, opticalFlow, euclidianDistance\n')]
import numpy as np import itertools as it import os from models.model import AbstractModel from distribution_estimation.approximator import LaplaceApproximation from distribution_estimation.sampler import MonteCarlo from distribution_estimation.kernel_optimiser import HyperParameterOptimiser n_classes = 10 class GaussianProcess(AbstractModel): def __init__(self, kernel='sqr_exp', distribution_estimation='analytic', num_classes=2): super(GaussianProcess, self).__init__('GaussianProcesses') self.n_classes = num_classes self.hyper_params = None self.kernel = self.build_kernel(kernel) self.cov_function = None self.latent_function = None if distribution_estimation == 'analytic': self.estimator = LaplaceApproximation() else: # TODO: try with a sampling procedure raise NotImplementedError self.sampler = MonteCarlo(num_sampling_steps=1000) self.optimiser = HyperParameterOptimiser() self.num_restarts_fitting = 1 def build_kernel(self, kernel='sqr_exp'): def squared_exponential(x_i, x_j, cls=0): d = x_i - x_j res = (self.hyper_params['sigma'][cls] ** 2) * \ np.exp(-0.5 * np.dot(d.T, d) / self.hyper_params['lambda'][cls]) return res def linear(x_i, x_j, cls=0): return self.hyper_params['sigma'][cls] ** 2 + np.dot(x_i.T, x_j) def periodic(x_i, x_j, cls=0): d = np.sin(0.5 * (x_i - x_j)) return np.exp(-2.0 * np.dot(d.T, d) / (self.hyper_params['lambda'][cls]) ** 2) if kernel == 'sqr_exp': # best for multi: 1 - 1,1 / 16,3, 16.4 if self.n_classes == 2: self.hyper_params = {'sigma': np.random.uniform(1.0, 1.1, size=n_classes if self.n_classes > 2 else 1), 'lambda': np.random.uniform(3.3, 3.4, size=n_classes if self.n_classes > 2 else 1)} else: self.hyper_params = {'sigma': np.random.uniform(0.5, 0.6, size=n_classes if self.n_classes > 2 else 1), 'lambda': np.random.uniform(16.3, 16.4, size=n_classes if self.n_classes > 2 else 1)} return squared_exponential elif kernel == 'lin': self.hyper_params = {'sigma': np.random.uniform(0.7, 1.3, size=n_classes if self.n_classes > 2 else 1)} return linear elif kernel == 'periodic': self.hyper_params = {'lambda': np.random.uniform(0.7, 1.3, size=n_classes if self.n_classes > 2 else 1)} return periodic else: raise NotImplementedError def build_cov_function(self, data=None, mode='symm'): if mode == 'hetero': if self.n_classes == 2: print("\t\tComputing the covariance between training " "and test samples for class {}".format(self.class_positive)) else: print("\t\tComputing the covariance between training and test samples") num_train_samples = self.data['x_train'].shape[0] num_samples_new = data.shape[0] if self.n_classes > 2: cov_function = [np.zeros((num_samples_new, num_train_samples)) for _ in xrange(self.n_classes)] for c in xrange(self.n_classes): for i in xrange(num_samples_new): for j in xrange(num_train_samples): cov_function[c][i, j] = self.kernel(data[i], self.data['x_train'][j], cls=c) else: cov_function = np.zeros((num_samples_new, num_train_samples)) for i in xrange(num_samples_new): for j in xrange(num_train_samples): cov_function[i, j] = self.kernel(data[i], self.data['x_train'][j]) elif mode == 'auto': if self.n_classes == 2: print("\t\tComputing the covariance between test samples for class {}".format(self.class_positive)) else: print("\t\tComputing the covariance between test samples") if self.n_classes > 2: cov_function = [np.array([self.kernel(data[i], data[i], cls=c) for i in xrange(data.shape[0])]) for c in xrange(n_classes)] else: cov_function = np.array([self.kernel(data[i], data[i]) for i in xrange(data.shape[0])]) elif mode == 'symm': if self.n_classes == 2: print("\t\tComputing the covariance between training samples for class {}".format(self.class_positive)) else: print("\t\tComputing the covariance between training samples") num_samples = data.shape[0] upper_tri_ids = it.combinations(np.arange(num_samples), 2) if self.n_classes > 2: cov_function = [np.zeros((num_samples, num_samples)) for _ in xrange(n_classes)] # compute upper triangular submatrix and then the lower using the symmetry property for c in xrange(n_classes): for i, j in upper_tri_ids: cov_function[c][i, j] = self.kernel(data[i], data[j], cls=c) cov_function[c] += cov_function[c].T # compute the diagonal for i in xrange(num_samples): cov_function[c][i, i] = self.kernel(data[i], data[i], cls=c) else: cov_function = np.zeros((num_samples, num_samples)) for i, j in upper_tri_ids: cov_function[i, j] = self.kernel(data[i], data[j]) cov_function += cov_function.T for i in xrange(num_samples): cov_function[i, i] = self.kernel(data[i], data[i]) else: raise ValueError return cov_function def set_gp_functions(self, latent_init=None, cov_init=None): if cov_init is None: self.cov_function = self.build_cov_function(self.data['x_train'], mode='symm') else: self.cov_function = cov_init if latent_init is None: if self.n_classes > 2: self.latent_function = np.zeros((n_classes, self.num_samples)) else: self.latent_function = np.zeros(self.num_samples) else: self.latent_function = latent_init def update_hypers_and_functions(self, new_hypers): self.hyper_params = new_hypers self.cov_function = self.build_cov_function(self.data['x_train'], mode='symm') def save_trainable_params(self): if self.n_classes == 2: path_to_params = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'optimal_f_' + str(self.class_positive) + '.npy') else: path_to_params = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'optimal_f.npy') np.save(path_to_params, self.latent_function) def load_trainable_params(self): def load_path_binary(): path = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'optimal_f_' + str(self.class_positive) + '.npy') return path if self.n_classes > 2: if self.classification_mode == 'multi': path_to_params = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'optimal_f.npy') else: for gp in self.binary_gps: gp.load_trainable_params() return else: path_to_params = load_path_binary() self.latent_function = np.load(path_to_params) def fit(self, train_data, **kwargs): pass def predict(self, new_data, **kwargs): pass class MulticlassGaussianProcess(GaussianProcess): def __init__(self, kernel='sqr_exp', distribution_estimation='analytic', classification_mode='mixed_binary', train_data_limit=None): super(MulticlassGaussianProcess, self).__init__(kernel=kernel, distribution_estimation=distribution_estimation, num_classes=n_classes) self.classification_mode = classification_mode # can be 'multi' but it is not finished self.train_data_limit = train_data_limit def _stratify_training_data(self, c, size=100): ids_of_class_c = np.arange(self.data['y_train'].shape[0])[self.data['y_train'] == c] ids_the_rest = np.arange(self.data['y_train'].shape[0])[self.data['y_train'] != c] # pick a random subset 50% of size from them size_of_class_c = size // 2 subset_ids_of_class_c = np.random.choice(ids_of_class_c, size=size_of_class_c, replace=False) subset_ids_rest = np.random.choice(ids_the_rest, size=size - size_of_class_c, replace=False) shuffled_order = np.random.permutation(subset_ids_of_class_c.shape[0] + subset_ids_rest.shape[0]) data_dict = {'x_train': np.vstack((self.data['x_train'][subset_ids_of_class_c], self.data['x_train'][subset_ids_rest]))[shuffled_order], 'y_train': np.hstack((self.data['y_train'][subset_ids_of_class_c], self.data['y_train'][subset_ids_rest]))[shuffled_order]} return data_dict def fit(self, train_data, **kwargs): """ Apply multi-class Laplace approximation with a squared expoenntial kernel covariance function. Use a shared signal amplitude and length-scale factors sigma and l for all 10 classes (i.e. latent functions) and all 28*28 input dimensions. :param train_data: :param kwargs: :return: """ self.data = train_data if self.classification_mode == 'multi': self.data['x_train'] = self.data['x_train'][:self.train_data_limit] self.data['y_train'] = self.data['y_train'][:self.train_data_limit] self.num_samples, dim_x, dim_y = self.data['x_train'].shape self.data['x_train'] = self.data['x_train'].reshape(self.num_samples, dim_x * dim_y) if self.classification_mode == 'multi': self.set_gp_functions() f_posterior, approx_log_marg_likelihood = \ self.estimator.approximate_multiclass(self.cov_function, self.data['y_train'], latent_init=self.latent_function) # better_hypers = self.optimiser.optimise_hyper_params_multiclass(f_posterior) # cov_posterior, mean_posterior = self._recompute_mean_cov(better_hypers) # self._set_gp_functions(latent_init=f_posterior, cov_init=cov_posterior) self.latent_function = f_posterior # self.save_trainable_params() elif self.classification_mode == 'mixed_binary': self.binary_gps = list() for cls in range(n_classes): train_data_for_c = self._stratify_training_data(c=cls, size=self.train_data_limit) gp = BinaryGaussianProcessClassifier(class_positive=cls) gp.fit(train_data_for_c) self.binary_gps.append(gp) else: raise ValueError def predict(self, new_data, **kwargs): if len(new_data.shape) == 3: num_samples, dim_x, dim_y = new_data.shape new_data = new_data.reshape(num_samples, dim_x * dim_y) else: num_samples = new_data.shape[0] if self.classification_mode == 'multi': cov_function_test = {'auto': self.build_cov_function(new_data, mode='auto'), 'hetero': self.build_cov_function(new_data, mode='hetero')} latent_mean, latent_cov = self.estimator.compute_latent_mean_cov_multiclass(cov_matrix_train=self.cov_function, cov_matrix_test=cov_function_test, f_posterior=self.latent_function) predicted_class_probs = self.sampler.sample(latent_mean=latent_mean, latent_cov=latent_cov) return np.argmax(predicted_class_probs, axis=1) elif self.classification_mode == 'mixed_binary': predictions = np.zeros((num_samples, n_classes)) for gp in self.binary_gps: predictions[:, gp.class_positive] = gp.predict(new_data, return_probs=True) prediction_classes = np.argmax(predictions, axis=1) else: raise ValueError return prediction_classes class BinaryGaussianProcessClassifier(GaussianProcess): def __init__(self, class_positive, kernel='sqr_exp', distribution_estimation='analytic'): super(BinaryGaussianProcessClassifier, self).__init__(kernel=kernel, distribution_estimation=distribution_estimation, num_classes=2) self.class_positive = class_positive self.iter_hyperopt = 0 def fit(self, train_data, **kwargs): self.data = train_data if len(self.data['x_train'].shape) == 3: self.num_samples, dim_x, dim_y = train_data.shape self.data = train_data.reshape(self.num_samples, dim_x * dim_y) self.num_samples = self.data['x_train'].shape[0] self.set_gp_functions() if self.iter_hyperopt == 0: f_posterior, a, approx_log_marg_likelihood = \ self.estimator.approximate_binary(self.cov_function, self.data['y_train'], latent_init=self.latent_function, cls=self.class_positive) self.latent_function = f_posterior else: for i in range(self.iter_hyperopt): f_posterior, a, approx_log_marg_likelihood = \ self.estimator.approximate_binary(self.cov_function, self.data['y_train'], latent_init=self.latent_function, cls=self.class_positive) better_hypers = self.optimiser.optimise_hyper_params_binary(self.cov_function, f_posterior, a, self.data['y_train'], self.hyper_params, self.class_positive) self.hyper_params = better_hypers self.set_gp_functions(latent_init=f_posterior) # it also recomputes the new covariance # self.save_trainable_params() def predict(self, new_data, **kwargs): # extend the covariance function cov_function_test = {'auto': self.build_cov_function(new_data, mode='auto'), 'hetero': self.build_cov_function(new_data, mode='hetero')} latent_mean, latent_cov = self.estimator.compute_latent_mean_cov_binary(cov_matrix_train=self.cov_function, cov_matrix_test=cov_function_test, f_posterior=self.latent_function) predict_probs = kwargs.get('return_probs', False) predicted_class_probs = self.estimator.approximate_posterior_integral(latent_mean=latent_mean, latent_cov=latent_cov) if predict_probs: return predicted_class_probs else: return (predicted_class_probs > 0.5).astype(np.int32) # return +1 for class_one and 0 otherwise if __name__ == "__main__": from utils.data_utils import load_MNIST data_train, data_test = load_MNIST(num_training=2000, num_validation=0) model = MulticlassGaussianProcess(classification_mode='multi') model.fit(data_train) predictions = model.predict(data_test['x_test']) test_acc = np.sum(predictions == data_test['y_test']) / float(predictions.shape[0]) * 100. print("Validation accuracy: {0}" .format(test_acc))
[ "numpy.random.uniform", "utils.data_utils.load_MNIST", "numpy.save", "numpy.load", "distribution_estimation.approximator.LaplaceApproximation", "numpy.sum", "numpy.argmax", "os.path.realpath", "numpy.zeros", "numpy.hstack", "numpy.random.permutation", "numpy.sin", "numpy.arange", "numpy.ra...
[((16242, 16289), 'utils.data_utils.load_MNIST', 'load_MNIST', ([], {'num_training': '(2000)', 'num_validation': '(0)'}), '(num_training=2000, num_validation=0)\n', (16252, 16289), False, 'from utils.data_utils import load_MNIST\n'), ((924, 959), 'distribution_estimation.sampler.MonteCarlo', 'MonteCarlo', ([], {'num_sampling_steps': '(1000)'}), '(num_sampling_steps=1000)\n', (934, 959), False, 'from distribution_estimation.sampler import MonteCarlo\n'), ((985, 1010), 'distribution_estimation.kernel_optimiser.HyperParameterOptimiser', 'HyperParameterOptimiser', ([], {}), '()\n', (1008, 1010), False, 'from distribution_estimation.kernel_optimiser import HyperParameterOptimiser\n'), ((7048, 7093), 'numpy.save', 'np.save', (['path_to_params', 'self.latent_function'], {}), '(path_to_params, self.latent_function)\n', (7055, 7093), True, 'import numpy as np\n'), ((7765, 7788), 'numpy.load', 'np.load', (['path_to_params'], {}), '(path_to_params)\n', (7772, 7788), True, 'import numpy as np\n'), ((8903, 8972), 'numpy.random.choice', 'np.random.choice', (['ids_of_class_c'], {'size': 'size_of_class_c', 'replace': '(False)'}), '(ids_of_class_c, size=size_of_class_c, replace=False)\n', (8919, 8972), True, 'import numpy as np\n'), ((8999, 9073), 'numpy.random.choice', 'np.random.choice', (['ids_the_rest'], {'size': '(size - size_of_class_c)', 'replace': '(False)'}), '(ids_the_rest, size=size - size_of_class_c, replace=False)\n', (9015, 9073), True, 'import numpy as np\n'), ((9099, 9184), 'numpy.random.permutation', 'np.random.permutation', (['(subset_ids_of_class_c.shape[0] + subset_ids_rest.shape[0])'], {}), '(subset_ids_of_class_c.shape[0] + subset_ids_rest.shape[0]\n )\n', (9120, 9184), True, 'import numpy as np\n'), ((776, 798), 'distribution_estimation.approximator.LaplaceApproximation', 'LaplaceApproximation', ([], {}), '()\n', (796, 798), False, 'from distribution_estimation.approximator import LaplaceApproximation\n'), ((1512, 1537), 'numpy.sin', 'np.sin', (['(0.5 * (x_i - x_j))'], {}), '(0.5 * (x_i - x_j))\n', (1518, 1537), True, 'import numpy as np\n'), ((8623, 8663), 'numpy.arange', 'np.arange', (["self.data['y_train'].shape[0]"], {}), "(self.data['y_train'].shape[0])\n", (8632, 8663), True, 'import numpy as np\n'), ((8714, 8754), 'numpy.arange', 'np.arange', (["self.data['y_train'].shape[0]"], {}), "(self.data['y_train'].shape[0])\n", (8723, 8754), True, 'import numpy as np\n'), ((12529, 12569), 'numpy.argmax', 'np.argmax', (['predicted_class_probs'], {'axis': '(1)'}), '(predicted_class_probs, axis=1)\n', (12538, 12569), True, 'import numpy as np\n'), ((16455, 16497), 'numpy.sum', 'np.sum', (["(predictions == data_test['y_test'])"], {}), "(predictions == data_test['y_test'])\n", (16461, 16497), True, 'import numpy as np\n'), ((1437, 1455), 'numpy.dot', 'np.dot', (['x_i.T', 'x_j'], {}), '(x_i.T, x_j)\n', (1443, 1455), True, 'import numpy as np\n'), ((3636, 3682), 'numpy.zeros', 'np.zeros', (['(num_samples_new, num_train_samples)'], {}), '((num_samples_new, num_train_samples))\n', (3644, 3682), True, 'import numpy as np\n'), ((6304, 6343), 'numpy.zeros', 'np.zeros', (['(n_classes, self.num_samples)'], {}), '((n_classes, self.num_samples))\n', (6312, 6343), True, 'import numpy as np\n'), ((6401, 6427), 'numpy.zeros', 'np.zeros', (['self.num_samples'], {}), '(self.num_samples)\n', (6409, 6427), True, 'import numpy as np\n'), ((9212, 9312), 'numpy.vstack', 'np.vstack', (["(self.data['x_train'][subset_ids_of_class_c], self.data['x_train'][\n subset_ids_rest])"], {}), "((self.data['x_train'][subset_ids_of_class_c], self.data['x_train'\n ][subset_ids_rest]))\n", (9221, 9312), True, 'import numpy as np\n'), ((9400, 9500), 'numpy.hstack', 'np.hstack', (["(self.data['y_train'][subset_ids_of_class_c], self.data['y_train'][\n subset_ids_rest])"], {}), "((self.data['y_train'][subset_ids_of_class_c], self.data['y_train'\n ][subset_ids_rest]))\n", (9409, 9500), True, 'import numpy as np\n'), ((12654, 12688), 'numpy.zeros', 'np.zeros', (['(num_samples, n_classes)'], {}), '((num_samples, n_classes))\n', (12662, 12688), True, 'import numpy as np\n'), ((12853, 12883), 'numpy.argmax', 'np.argmax', (['predictions'], {'axis': '(1)'}), '(predictions, axis=1)\n', (12862, 12883), True, 'import numpy as np\n'), ((1783, 1855), 'numpy.random.uniform', 'np.random.uniform', (['(1.0)', '(1.1)'], {'size': '(n_classes if self.n_classes > 2 else 1)'}), '(1.0, 1.1, size=n_classes if self.n_classes > 2 else 1)\n', (1800, 1855), True, 'import numpy as np\n'), ((1904, 1976), 'numpy.random.uniform', 'np.random.uniform', (['(3.3)', '(3.4)'], {'size': '(n_classes if self.n_classes > 2 else 1)'}), '(3.3, 3.4, size=n_classes if self.n_classes > 2 else 1)\n', (1921, 1976), True, 'import numpy as np\n'), ((2042, 2114), 'numpy.random.uniform', 'np.random.uniform', (['(0.5)', '(0.6)'], {'size': '(n_classes if self.n_classes > 2 else 1)'}), '(0.5, 0.6, size=n_classes if self.n_classes > 2 else 1)\n', (2059, 2114), True, 'import numpy as np\n'), ((2163, 2237), 'numpy.random.uniform', 'np.random.uniform', (['(16.3)', '(16.4)'], {'size': '(n_classes if self.n_classes > 2 else 1)'}), '(16.3, 16.4, size=n_classes if self.n_classes > 2 else 1)\n', (2180, 2237), True, 'import numpy as np\n'), ((2350, 2422), 'numpy.random.uniform', 'np.random.uniform', (['(0.7)', '(1.3)'], {'size': '(n_classes if self.n_classes > 2 else 1)'}), '(0.7, 1.3, size=n_classes if self.n_classes > 2 else 1)\n', (2367, 2422), True, 'import numpy as np\n'), ((3239, 3285), 'numpy.zeros', 'np.zeros', (['(num_samples_new, num_train_samples)'], {}), '((num_samples_new, num_train_samples))\n', (3247, 3285), True, 'import numpy as np\n'), ((6801, 6827), 'os.path.realpath', 'os.path.realpath', (['__file__'], {}), '(__file__)\n', (6817, 6827), False, 'import os\n'), ((6994, 7020), 'os.path.realpath', 'os.path.realpath', (['__file__'], {}), '(__file__)\n', (7010, 7020), False, 'import os\n'), ((7213, 7239), 'os.path.realpath', 'os.path.realpath', (['__file__'], {}), '(__file__)\n', (7229, 7239), False, 'import os\n'), ((1571, 1585), 'numpy.dot', 'np.dot', (['d.T', 'd'], {}), '(d.T, d)\n', (1577, 1585), True, 'import numpy as np\n'), ((2528, 2600), 'numpy.random.uniform', 'np.random.uniform', (['(0.7)', '(1.3)'], {'size': '(n_classes if self.n_classes > 2 else 1)'}), '(0.7, 1.3, size=n_classes if self.n_classes > 2 else 1)\n', (2545, 2600), True, 'import numpy as np\n'), ((4851, 4873), 'numpy.arange', 'np.arange', (['num_samples'], {}), '(num_samples)\n', (4860, 4873), True, 'import numpy as np\n'), ((5570, 5606), 'numpy.zeros', 'np.zeros', (['(num_samples, num_samples)'], {}), '((num_samples, num_samples))\n', (5578, 5606), True, 'import numpy as np\n'), ((7494, 7520), 'os.path.realpath', 'os.path.realpath', (['__file__'], {}), '(__file__)\n', (7510, 7520), False, 'import os\n'), ((1267, 1281), 'numpy.dot', 'np.dot', (['d.T', 'd'], {}), '(d.T, d)\n', (1273, 1281), True, 'import numpy as np\n'), ((4945, 4981), 'numpy.zeros', 'np.zeros', (['(num_samples, num_samples)'], {}), '((num_samples, num_samples))\n', (4953, 4981), True, 'import numpy as np\n')]
# Copyright 2018 <NAME> & <NAME>. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS-IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # -*- coding: utf-8 -*- import numpy as np import warnings import random from sklearn.manifold import TSNE, MDS from sklearn.decomposition import PCA import matplotlib.pyplot as plt from scipy import stats import pandas as pd from sklearn.preprocessing import minmax_scale import keras # 生成样本 def generate_sample(x, y, N_classes=None, sample_num=None, have_correct=True): ''' :param x: 特征 :param y: 标签 :param N_classes: 类别个数 :param sample_num: 样本个数 :param have_correct: 是否必包括正确标记 :return: 生成的特征,生成的标签,是否为该类 ''' x, y = np.array(x), np.array(y).astype(np.int32) if N_classes is None: N_classes = y.max() + 1 if len(y.shape) == 1: y = keras.utils.to_categorical(y, N_classes) if sample_num is None: sample_num = N_classes assert sample_num > 0 # 生成的样本必须大于0个 assert len(y.shape) == 2 # 转化后的标记的维度必须为2 data, label, is_True = [], [], [] for i in range(x.shape[0]): samples = list(np.random.choice(N_classes, size=sample_num, replace=True)) if have_correct: samples.append(np.argmax(y[i])) samples = samples[1:] for j in range(sample_num): data.append(x[i]) label.append(samples[j]) if y[i, samples[j]] == 1: is_True.append(True) else: is_True.append(False) return np.array(data), np.array(label), np.array(is_True) # 生成迭代器 def data_iter(data, label, batch_size, is_True=None): ''' :param data: 样本数据 :param label: 样本标签 :param batch_size: 批大小 :param is_True: 标记是否为真 :return: 迭代器 ''' data, label = np.array(data), np.array(label) n_samples = data.shape[0] idx = list(range(n_samples)) random.shuffle(idx) if is_True is not None: is_True = np.array(is_True) for i in range(0, n_samples, batch_size): j = np.array(idx[i:min(i + batch_size, n_samples)]) yield np.take(data, j, 0), np.take(label, j, 0), np.take(is_True, j, 0) else: for i in range(0, n_samples, batch_size): j = np.array(idx[i:min(i + batch_size, n_samples)]) yield np.take(data, j, 0), np.take(label, j, 0) # label转one-hot def to_categorical(label, num_classes=None): ''' :param label: 样本标签 :param num_classes: 总共的类别数 :return: 标签的one-hot编码 ''' label = np.array(label, dtype='int') if num_classes is not None: assert num_classes > label.max() # 类别数量错误 else: num_classes = label.max() + 1 if len(label.shape) == 1: y = np.eye(num_classes, dtype='int64')[label] return y elif len(label.shape) == 2 and label.shape[1] == 1: y = np.eye(num_classes, dtype='int64')[label.squeeze()] return y else: warnings.warn('Warning: one_hot_to_label do not work') return label # one-hot转label def one_hot_to_label(y): ''' :param y: one-hot编码 :return: 标签 ''' y = np.array(y) if len(y.shape) == 2 and y.max() == 1 and y.sum(1).mean() == 1: return y.argmax(1) else: warnings.warn('Warning: one_hot_to_label do not work') return y # 画出样本数据示意图 def plot(x, y, method='t-SNE'): ''' :param x: 数据 :param y: 标签 :param method: 可视化方法,包括['t-SNE','PCA','MDS'] :return: None ''' x, y = check_data_target(x, y) if method == 't-SNE': x = TSNE(n_components=2).fit_transform(x) elif method == 'PCA' or method == 'pca': x = PCA(n_components=2).fit_transform(x) elif method == 'MDS' or method == 'mds': x = MDS(n_components=2).fit_transform(x) else: warnings.warn('Wrong method!') return for i in range(y.max() + 1): plt.scatter(x[y == i][:, 0], x[y == i][:, 1], label='class %d' % i) plt.legend() plt.show() # 画出分类边界图 def plot_classifier(classifier, x, y): ''' :param classifier: 分类器 :param x: 数据 :param y: 标签 :return: None ''' x, y = check_data_target(x, y) x1_min, x1_max = np.min(x[:, 0]) - 1, np.max(x[:, 0]) + 1 x2_min, x2_max = np.min(x[:, 1]) - 1, np.max(x[:, 1]) + 1 step_size = 0.01 x1_values, x2_values = np.meshgrid(np.arange(x1_min, x1_max, step_size), np.arange(x2_min, x2_max, step_size)) mesh_output = classifier.predict(np.c_[x1_values.ravel(), x2_values.ravel()]) mesh_output = mesh_output.reshape(x1_values.shape) plt.figure() plt.pcolormesh(x1_values, x2_values, mesh_output, cmap=plt.cm.gray) plt.scatter(x[:, 0], x[:, 1], c=y, s=80, linewidths=1, cmap=plt.cm.Paired) plt.xlim(x1_values.min(), x1_values.max()) plt.ylim(x2_values.min(), x2_values.max()) plt.xticks((np.arange(int(np.min(x[:, 0]) - 1), int(np.max(x[:, 0]) + 1), 1))) plt.yticks((np.arange(int(np.min(x[:, 1]) - 1), int(np.max(x[:, 1]) + 1), 1))) plt.show() # 检查数据和标签的形状 def check_data_target(x, y): ''' :param x: 数据 :param y: 标签 :return: 数据、标签 ''' x, y = np.array(x), np.array(y) assert x.ndim == 2 # 数据形状错误 assert y.ndim == 1 or (y.ndim == 2 and y.shape[1] == 1) # 标签形状错误 if y.ndim == 2 and y.shape[1] == 1: y = y.squeeze() return x, y # Friedman检验 def Friedman_test(x, alpha=0.05, ranked=False, use_f_distribution=False, verbose=False): ''' :param x: 各个算法在不同数据集上的得分或排序,形状为[数据集个数,算法个数] :param alpha: 显著性水平 :param ranked: 输入的数据是否为排序 :param use_f_distribution: 是否使用改进的Friedman检测 :param verbose: 当输入数据为得分时,是否打印排序结果 :return: 各算法的排序 ''' x = np.array(x) + 0. n_datasets, n_algorithms = x.shape[0], x.shape[1] if not ranked: # 输入为得分 for i in range(n_datasets): # 对于第i个数据集 rank_list = np.zeros([n_algorithms]) # 不同算法的排名 score = x[i].copy() chuli = 0 while chuli != n_algorithms: M = np.max(score) score_equal = [] for j in range(n_algorithms): if score[j] == M: score_equal.append(j) rank_list[score_equal] = np.sum(np.arange(chuli + 1, chuli + 1 + len(score_equal))) / len(score_equal) score[score_equal] = -np.inf x[i] = rank_list.copy() chuli += len(score_equal) if verbose: print('输入得分排名为:') print(x) R = np.mean(x, axis=0) Tao = 12 * n_datasets / n_algorithms / (n_algorithms + 1) * np.sum(np.square(R - (n_algorithms + 1) / 2)) if use_f_distribution: # 使用改进的Friedman检测 F = stats.f.isf(q=alpha, dfn=(n_algorithms - 1), dfd=int(n_algorithms - 1) * (n_datasets - 1)) Tao = (n_datasets - 1) * Tao / (n_datasets * (n_algorithms - 1) - Tao) if Tao > F: print('Tao值为%.4f,显著性水平为%.4f的F分布值为%.4f,有显著区别' % (Tao, alpha, F)) else: print('Tao值为%.4f,显著性水平为%.4f的F分布值为%.4f,无显著区别' % (Tao, alpha, F)) else: # 使用传统的Friedman检测 Chi2 = stats.chi2.isf(q=alpha, df=n_algorithms - 1) if Tao > Chi2: print('Tao值为%.4f,显著性水平为%.4f的卡方分布值为%.4f,有显著区别' % (Tao, alpha, Chi2)) else: print('Tao值为%.4f,显著性水平为%.4f的卡方分布值为%.4f,无显著区别' % (Tao, alpha, Chi2)) return x # t检验 def t_test(x1=None, x2=None, alpha=0.05, from_stats=False, mean1=None, std1=None, nobs1=None, mean2=None, std2=None, nobs2=None): ''' :param x1: 第一组准确率,list或numpy.array :param x2: 第二组准确率,list或numpy.array :param alpha:显著性水平 :param from_stats: 输入的参数是否为统计学参数 :param mean1: 第一组样本的均值 :param std1: 第一组样本的方差 :param nobs1: 第一组样本个数 :param mean2: 第二组样本的均值 :param std2: 第二组样本的方差 :param nobs2: 第二组样本个数 :return: 显著程度 ''' if from_stats: std1, std2 = np.sqrt(nobs1 / (nobs1 - 1)) * std1, np.sqrt(nobs2 / (nobs2 - 1)) * std2 statistic, pvalue = stats.ttest_ind_from_stats(mean1=mean1, std1=std1, nobs1=nobs1, mean2=mean2, std2=std2, nobs2=nobs2) else: x1, x2 = np.array(x1), np.array(x2) statistic, pvalue = stats.levene(x1, x2) print(pvalue) if pvalue > 0.05: equal_val = True else: equal_val = False statistic, pvalue = stats.ttest_ind(x1, x2, equal_var=equal_val) if pvalue > alpha: print('pvalue值为%.4f,显著性水平为%.4f,无显著区别' % (pvalue, alpha)) else: print('pvalue值为%.4f,显著性水平为%.4f,有显著区别' % (pvalue, alpha)) return pvalue # 计算Gram矩阵 def Gram(x): ''' :param x: 输入向量 :return: 输入向量对应的Gram矩阵 ''' x = np.array(x).squeeze() assert len(x.shape) == 1 # 样本维度不符 return x.reshape(-1, 1) * x # pandas DataFrame数据预处理 def data_preprocessing(data): ''' :param data: Pandas DataFrame :return: 处理后的numpy二维数组 ''' data = pd.get_dummies(data) data = data.fillna(data.mean()) return minmax_scale(np.array(data))
[ "numpy.argmax", "random.shuffle", "scipy.stats.levene", "matplotlib.pyplot.figure", "numpy.mean", "numpy.arange", "sklearn.manifold.MDS", "scipy.stats.ttest_ind_from_stats", "numpy.max", "numpy.random.choice", "keras.utils.to_categorical", "matplotlib.pyplot.show", "pandas.get_dummies", "m...
[((2423, 2442), 'random.shuffle', 'random.shuffle', (['idx'], {}), '(idx)\n', (2437, 2442), False, 'import random\n'), ((3079, 3107), 'numpy.array', 'np.array', (['label'], {'dtype': '"""int"""'}), "(label, dtype='int')\n", (3087, 3107), True, 'import numpy as np\n'), ((3700, 3711), 'numpy.array', 'np.array', (['y'], {}), '(y)\n', (3708, 3711), True, 'import numpy as np\n'), ((4564, 4576), 'matplotlib.pyplot.legend', 'plt.legend', ([], {}), '()\n', (4574, 4576), True, 'import matplotlib.pyplot as plt\n'), ((4582, 4592), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (4590, 4592), True, 'import matplotlib.pyplot as plt\n'), ((5193, 5205), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (5203, 5205), True, 'import matplotlib.pyplot as plt\n'), ((5211, 5278), 'matplotlib.pyplot.pcolormesh', 'plt.pcolormesh', (['x1_values', 'x2_values', 'mesh_output'], {'cmap': 'plt.cm.gray'}), '(x1_values, x2_values, mesh_output, cmap=plt.cm.gray)\n', (5225, 5278), True, 'import matplotlib.pyplot as plt\n'), ((5284, 5358), 'matplotlib.pyplot.scatter', 'plt.scatter', (['x[:, 0]', 'x[:, 1]'], {'c': 'y', 's': '(80)', 'linewidths': '(1)', 'cmap': 'plt.cm.Paired'}), '(x[:, 0], x[:, 1], c=y, s=80, linewidths=1, cmap=plt.cm.Paired)\n', (5295, 5358), True, 'import matplotlib.pyplot as plt\n'), ((5628, 5638), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (5636, 5638), True, 'import matplotlib.pyplot as plt\n'), ((7181, 7199), 'numpy.mean', 'np.mean', (['x'], {'axis': '(0)'}), '(x, axis=0)\n', (7188, 7199), True, 'import numpy as np\n'), ((9681, 9701), 'pandas.get_dummies', 'pd.get_dummies', (['data'], {}), '(data)\n', (9695, 9701), True, 'import pandas as pd\n'), ((1197, 1208), 'numpy.array', 'np.array', (['x'], {}), '(x)\n', (1205, 1208), True, 'import numpy as np\n'), ((1339, 1379), 'keras.utils.to_categorical', 'keras.utils.to_categorical', (['y', 'N_classes'], {}), '(y, N_classes)\n', (1365, 1379), False, 'import keras\n'), ((2044, 2058), 'numpy.array', 'np.array', (['data'], {}), '(data)\n', (2052, 2058), True, 'import numpy as np\n'), ((2060, 2075), 'numpy.array', 'np.array', (['label'], {}), '(label)\n', (2068, 2075), True, 'import numpy as np\n'), ((2077, 2094), 'numpy.array', 'np.array', (['is_True'], {}), '(is_True)\n', (2085, 2094), True, 'import numpy as np\n'), ((2321, 2335), 'numpy.array', 'np.array', (['data'], {}), '(data)\n', (2329, 2335), True, 'import numpy as np\n'), ((2337, 2352), 'numpy.array', 'np.array', (['label'], {}), '(label)\n', (2345, 2352), True, 'import numpy as np\n'), ((2491, 2508), 'numpy.array', 'np.array', (['is_True'], {}), '(is_True)\n', (2499, 2508), True, 'import numpy as np\n'), ((3829, 3883), 'warnings.warn', 'warnings.warn', (['"""Warning: one_hot_to_label do not work"""'], {}), "('Warning: one_hot_to_label do not work')\n", (3842, 3883), False, 'import warnings\n'), ((4491, 4558), 'matplotlib.pyplot.scatter', 'plt.scatter', (['x[y == i][:, 0]', 'x[y == i][:, 1]'], {'label': "('class %d' % i)"}), "(x[y == i][:, 0], x[y == i][:, 1], label='class %d' % i)\n", (4502, 4558), True, 'import matplotlib.pyplot as plt\n'), ((4973, 5009), 'numpy.arange', 'np.arange', (['x1_min', 'x1_max', 'step_size'], {}), '(x1_min, x1_max, step_size)\n', (4982, 5009), True, 'import numpy as np\n'), ((5011, 5047), 'numpy.arange', 'np.arange', (['x2_min', 'x2_max', 'step_size'], {}), '(x2_min, x2_max, step_size)\n', (5020, 5047), True, 'import numpy as np\n'), ((5773, 5784), 'numpy.array', 'np.array', (['x'], {}), '(x)\n', (5781, 5784), True, 'import numpy as np\n'), ((5786, 5797), 'numpy.array', 'np.array', (['y'], {}), '(y)\n', (5794, 5797), True, 'import numpy as np\n'), ((6337, 6348), 'numpy.array', 'np.array', (['x'], {}), '(x)\n', (6345, 6348), True, 'import numpy as np\n'), ((7778, 7822), 'scipy.stats.chi2.isf', 'stats.chi2.isf', ([], {'q': 'alpha', 'df': '(n_algorithms - 1)'}), '(q=alpha, df=n_algorithms - 1)\n', (7792, 7822), False, 'from scipy import stats\n'), ((8679, 8783), 'scipy.stats.ttest_ind_from_stats', 'stats.ttest_ind_from_stats', ([], {'mean1': 'mean1', 'std1': 'std1', 'nobs1': 'nobs1', 'mean2': 'mean2', 'std2': 'std2', 'nobs2': 'nobs2'}), '(mean1=mean1, std1=std1, nobs1=nobs1, mean2=mean2,\n std2=std2, nobs2=nobs2)\n', (8705, 8783), False, 'from scipy import stats\n'), ((8921, 8941), 'scipy.stats.levene', 'stats.levene', (['x1', 'x2'], {}), '(x1, x2)\n', (8933, 8941), False, 'from scipy import stats\n'), ((9097, 9141), 'scipy.stats.ttest_ind', 'stats.ttest_ind', (['x1', 'x2'], {'equal_var': 'equal_val'}), '(x1, x2, equal_var=equal_val)\n', (9112, 9141), False, 'from scipy import stats\n'), ((9764, 9778), 'numpy.array', 'np.array', (['data'], {}), '(data)\n', (9772, 9778), True, 'import numpy as np\n'), ((1625, 1683), 'numpy.random.choice', 'np.random.choice', (['N_classes'], {'size': 'sample_num', 'replace': '(True)'}), '(N_classes, size=sample_num, replace=True)\n', (1641, 1683), True, 'import numpy as np\n'), ((3287, 3321), 'numpy.eye', 'np.eye', (['num_classes'], {'dtype': '"""int64"""'}), "(num_classes, dtype='int64')\n", (3293, 3321), True, 'import numpy as np\n'), ((3507, 3561), 'warnings.warn', 'warnings.warn', (['"""Warning: one_hot_to_label do not work"""'], {}), "('Warning: one_hot_to_label do not work')\n", (3520, 3561), False, 'import warnings\n'), ((4807, 4822), 'numpy.min', 'np.min', (['x[:, 0]'], {}), '(x[:, 0])\n', (4813, 4822), True, 'import numpy as np\n'), ((4828, 4843), 'numpy.max', 'np.max', (['x[:, 0]'], {}), '(x[:, 0])\n', (4834, 4843), True, 'import numpy as np\n'), ((4870, 4885), 'numpy.min', 'np.min', (['x[:, 1]'], {}), '(x[:, 1])\n', (4876, 4885), True, 'import numpy as np\n'), ((4891, 4906), 'numpy.max', 'np.max', (['x[:, 1]'], {}), '(x[:, 1])\n', (4897, 4906), True, 'import numpy as np\n'), ((6512, 6536), 'numpy.zeros', 'np.zeros', (['[n_algorithms]'], {}), '([n_algorithms])\n', (6520, 6536), True, 'import numpy as np\n'), ((7272, 7309), 'numpy.square', 'np.square', (['(R - (n_algorithms + 1) / 2)'], {}), '(R - (n_algorithms + 1) / 2)\n', (7281, 7309), True, 'import numpy as np\n'), ((8865, 8877), 'numpy.array', 'np.array', (['x1'], {}), '(x1)\n', (8873, 8877), True, 'import numpy as np\n'), ((8879, 8891), 'numpy.array', 'np.array', (['x2'], {}), '(x2)\n', (8887, 8891), True, 'import numpy as np\n'), ((9433, 9444), 'numpy.array', 'np.array', (['x'], {}), '(x)\n', (9441, 9444), True, 'import numpy as np\n'), ((1210, 1221), 'numpy.array', 'np.array', (['y'], {}), '(y)\n', (1218, 1221), True, 'import numpy as np\n'), ((1739, 1754), 'numpy.argmax', 'np.argmax', (['y[i]'], {}), '(y[i])\n', (1748, 1754), True, 'import numpy as np\n'), ((3417, 3451), 'numpy.eye', 'np.eye', (['num_classes'], {'dtype': '"""int64"""'}), "(num_classes, dtype='int64')\n", (3423, 3451), True, 'import numpy as np\n'), ((4151, 4171), 'sklearn.manifold.TSNE', 'TSNE', ([], {'n_components': '(2)'}), '(n_components=2)\n', (4155, 4171), False, 'from sklearn.manifold import TSNE, MDS\n'), ((4401, 4431), 'warnings.warn', 'warnings.warn', (['"""Wrong method!"""'], {}), "('Wrong method!')\n", (4414, 4431), False, 'import warnings\n'), ((6667, 6680), 'numpy.max', 'np.max', (['score'], {}), '(score)\n', (6673, 6680), True, 'import numpy as np\n'), ((8577, 8605), 'numpy.sqrt', 'np.sqrt', (['(nobs1 / (nobs1 - 1))'], {}), '(nobs1 / (nobs1 - 1))\n', (8584, 8605), True, 'import numpy as np\n'), ((8614, 8642), 'numpy.sqrt', 'np.sqrt', (['(nobs2 / (nobs2 - 1))'], {}), '(nobs2 / (nobs2 - 1))\n', (8621, 8642), True, 'import numpy as np\n'), ((2644, 2663), 'numpy.take', 'np.take', (['data', 'j', '(0)'], {}), '(data, j, 0)\n', (2651, 2663), True, 'import numpy as np\n'), ((2665, 2685), 'numpy.take', 'np.take', (['label', 'j', '(0)'], {}), '(label, j, 0)\n', (2672, 2685), True, 'import numpy as np\n'), ((2687, 2709), 'numpy.take', 'np.take', (['is_True', 'j', '(0)'], {}), '(is_True, j, 0)\n', (2694, 2709), True, 'import numpy as np\n'), ((2856, 2875), 'numpy.take', 'np.take', (['data', 'j', '(0)'], {}), '(data, j, 0)\n', (2863, 2875), True, 'import numpy as np\n'), ((2877, 2897), 'numpy.take', 'np.take', (['label', 'j', '(0)'], {}), '(label, j, 0)\n', (2884, 2897), True, 'import numpy as np\n'), ((4248, 4267), 'sklearn.decomposition.PCA', 'PCA', ([], {'n_components': '(2)'}), '(n_components=2)\n', (4251, 4267), False, 'from sklearn.decomposition import PCA\n'), ((5486, 5501), 'numpy.min', 'np.min', (['x[:, 0]'], {}), '(x[:, 0])\n', (5492, 5501), True, 'import numpy as np\n'), ((5512, 5527), 'numpy.max', 'np.max', (['x[:, 0]'], {}), '(x[:, 0])\n', (5518, 5527), True, 'import numpy as np\n'), ((5570, 5585), 'numpy.min', 'np.min', (['x[:, 1]'], {}), '(x[:, 1])\n', (5576, 5585), True, 'import numpy as np\n'), ((5596, 5611), 'numpy.max', 'np.max', (['x[:, 1]'], {}), '(x[:, 1])\n', (5602, 5611), True, 'import numpy as np\n'), ((4344, 4363), 'sklearn.manifold.MDS', 'MDS', ([], {'n_components': '(2)'}), '(n_components=2)\n', (4347, 4363), False, 'from sklearn.manifold import TSNE, MDS\n')]
# -*- coding: utf-8 -*- """ Created on Thu Apr 30 00:52:00 2015 @author: Ziang """ import numpy as np from sklearn import datasets from sklearn.svm import SVC from sklearn.linear_model import LogisticRegression from sklearn.ensemble import RandomForestClassifier import matplotlib import matplotlib.pyplot as plt from matplotlib.colors import ListedColormap from GPSVI.core.GPClassifier import GPClassifier from sklearn.cross_validation import train_test_split np.random.seed(0) xdata, ydata = datasets.make_moons(n_samples=400, noise=0.1) #xdata, ydata = datasets.make_circles(n_samples=800, noise=0.1, factor=0.5) xTr, xTe, yTr, yTe = train_test_split(xdata, ydata, test_size=0.50) x_min, x_max = xdata[:, 0].min() - .5, xdata[:, 0].max() + .5 y_min, y_max = xdata[:, 1].min() - .5, xdata[:, 1].max() + .5 h = 0.1 xx, yy = np.meshgrid(np.arange(x_min, x_max, h), np.arange(y_min, y_max, h)) #%% draw dataset plt.figure('Decision Boundary') cm = plt.cm.RdBu cm_bright = ListedColormap(['#d7191c', '#2b83ba']) #plt.subplot(221) #plt.scatter(xTe[:, 0], xTe[:, 1], c=yTe, cmap=cm_bright, alpha=0.5) #plt.scatter(xTe[:, 0], xTe[:, 1], c=yTe, cmap=cm_bright) #plt.xlim(xx.min(), xx.max()) #plt.ylim(yy.min(), yy.max()) #%% gp svi clf_gp = GPClassifier(xTr, yTr, \ alpha=0.2, max_iter=10000, num_inducing_points=200, \ kernel_type='rbf', kernel_args={'gamma':4.0}, \ learning_rate=0.01, verbose=2) clf_gp.fit() score = clf_gp.score(xTe, yTe) zz = clf_gp.predict_proba(np.c_[xx.ravel(), yy.ravel()]) zz = (zz[:,1] / np.sum(zz, axis=1)).reshape(xx.shape) plt.figure('Decision Boundary') ax = plt.subplot(2,2,1) ax.contourf(xx, yy, zz, cmap=cm, alpha=.6) #ax.scatter(xTr[:, 0], xTr[:, 1], c=yTr, cmap=cm_bright, alpha=0.2) ax.scatter(xTe[:, 0], xTe[:, 1], c=yTe, cmap=cm_bright, alpha=0.3) hx, hy = clf_gp.get_inducing_points() ax.scatter(hx[:, 0], hx[:, 1], marker='s', c=hy, cmap=cm_bright) ax.set_xlim(xx.min(), xx.max()) ax.set_ylim(yy.min(), yy.max()) ax.set_title('GP SVI') ax.text(xx.max() - .3, yy.min() + .3, ('%.2f' % score).lstrip('0'), size=15, horizontalalignment='right') #%% train benchmark classifier names = ['RBF SVM', 'Logistic Regression', 'Random Forest'] classifiers = [SVC(), LogisticRegression(), RandomForestClassifier()] i = 2 for name, clf in zip(names, classifiers): clf.fit(xTr, yTr) score = clf.score(xTe, yTe) if hasattr(clf, "decision_function"): zz = clf.decision_function(np.c_[xx.ravel(), yy.ravel()]) else: zz = clf.predict_proba(np.c_[xx.ravel(), yy.ravel()])[:, 1] zz = zz.reshape(xx.shape) plt.figure('Decision Boundary') ax = plt.subplot(2,2,i) ax.contourf(xx, yy, zz, cmap=cm, alpha=.6) # ax.scatter(xTr[:, 0], xTr[:, 1], c=yTr, cmap=cm_bright, alpha=0.5) ax.scatter(xTe[:, 0], xTe[:, 1], c=yTe, cmap=cm_bright, alpha=1) ax.set_xlim(xx.min(), xx.max()) ax.set_ylim(yy.min(), yy.max()) ax.set_title(name) ax.text(xx.max() - .3, yy.min() + .3, ('%.2f' % score).lstrip('0'), size=15, horizontalalignment='right') i += 1
[ "sklearn.ensemble.RandomForestClassifier", "sklearn.cross_validation.train_test_split", "matplotlib.pyplot.subplot", "numpy.random.seed", "numpy.sum", "GPSVI.core.GPClassifier.GPClassifier", "sklearn.datasets.make_moons", "matplotlib.pyplot.figure", "sklearn.linear_model.LogisticRegression", "nump...
[((463, 480), 'numpy.random.seed', 'np.random.seed', (['(0)'], {}), '(0)\n', (477, 480), True, 'import numpy as np\n'), ((497, 542), 'sklearn.datasets.make_moons', 'datasets.make_moons', ([], {'n_samples': '(400)', 'noise': '(0.1)'}), '(n_samples=400, noise=0.1)\n', (516, 542), False, 'from sklearn import datasets\n'), ((641, 686), 'sklearn.cross_validation.train_test_split', 'train_test_split', (['xdata', 'ydata'], {'test_size': '(0.5)'}), '(xdata, ydata, test_size=0.5)\n', (657, 686), False, 'from sklearn.cross_validation import train_test_split\n'), ((915, 946), 'matplotlib.pyplot.figure', 'plt.figure', (['"""Decision Boundary"""'], {}), "('Decision Boundary')\n", (925, 946), True, 'import matplotlib.pyplot as plt\n'), ((976, 1014), 'matplotlib.colors.ListedColormap', 'ListedColormap', (["['#d7191c', '#2b83ba']"], {}), "(['#d7191c', '#2b83ba'])\n", (990, 1014), False, 'from matplotlib.colors import ListedColormap\n'), ((1241, 1401), 'GPSVI.core.GPClassifier.GPClassifier', 'GPClassifier', (['xTr', 'yTr'], {'alpha': '(0.2)', 'max_iter': '(10000)', 'num_inducing_points': '(200)', 'kernel_type': '"""rbf"""', 'kernel_args': "{'gamma': 4.0}", 'learning_rate': '(0.01)', 'verbose': '(2)'}), "(xTr, yTr, alpha=0.2, max_iter=10000, num_inducing_points=200,\n kernel_type='rbf', kernel_args={'gamma': 4.0}, learning_rate=0.01,\n verbose=2)\n", (1253, 1401), False, 'from GPSVI.core.GPClassifier import GPClassifier\n'), ((1620, 1651), 'matplotlib.pyplot.figure', 'plt.figure', (['"""Decision Boundary"""'], {}), "('Decision Boundary')\n", (1630, 1651), True, 'import matplotlib.pyplot as plt\n'), ((1657, 1677), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(2)', '(2)', '(1)'], {}), '(2, 2, 1)\n', (1668, 1677), True, 'import matplotlib.pyplot as plt\n'), ((841, 867), 'numpy.arange', 'np.arange', (['x_min', 'x_max', 'h'], {}), '(x_min, x_max, h)\n', (850, 867), True, 'import numpy as np\n'), ((869, 895), 'numpy.arange', 'np.arange', (['y_min', 'y_max', 'h'], {}), '(y_min, y_max, h)\n', (878, 895), True, 'import numpy as np\n'), ((2269, 2274), 'sklearn.svm.SVC', 'SVC', ([], {}), '()\n', (2272, 2274), False, 'from sklearn.svm import SVC\n'), ((2276, 2296), 'sklearn.linear_model.LogisticRegression', 'LogisticRegression', ([], {}), '()\n', (2294, 2296), False, 'from sklearn.linear_model import LogisticRegression\n'), ((2298, 2322), 'sklearn.ensemble.RandomForestClassifier', 'RandomForestClassifier', ([], {}), '()\n', (2320, 2322), False, 'from sklearn.ensemble import RandomForestClassifier\n'), ((2646, 2677), 'matplotlib.pyplot.figure', 'plt.figure', (['"""Decision Boundary"""'], {}), "('Decision Boundary')\n", (2656, 2677), True, 'import matplotlib.pyplot as plt\n'), ((2687, 2707), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(2)', '(2)', 'i'], {}), '(2, 2, i)\n', (2698, 2707), True, 'import matplotlib.pyplot as plt\n'), ((1582, 1600), 'numpy.sum', 'np.sum', (['zz'], {'axis': '(1)'}), '(zz, axis=1)\n', (1588, 1600), True, 'import numpy as np\n')]
#!/usr/bin/env python # coding: utf-8 # In[2]: import gym import numpy as np import json from stable_baselines.sac.policies import MlpPolicy as MlpPolicy_SAC from stable_baselines import SAC from citylearn import CityLearn import matplotlib.pyplot as plt from pathlib import Path import time # In[3]: # Central agent controlling one of the buildings using the OpenAI Stable Baselines climate_zone = 1 data_path = Path("data/Climate_Zone_"+str(climate_zone)) building_attributes = data_path / 'building_attributes.json' weather_file = data_path / 'weather_data.csv' solar_profile = data_path / 'solar_generation_1kW.csv' building_state_actions = 'buildings_state_action_space.json' building_ids = ['Building_3'] objective_function = ['ramping','1-load_factor','average_daily_peak','peak_demand','net_electricity_consumption','quadratic'] # In[4]: params = {"non_shiftable_load": False, "month": True, "solar_gen": True, "t_out_pred_12h": False, "t_out_pred_6h": True} for p_key in params: print("Testing Parameter %s" % (p_key)) p_val = params[p_key] with open(building_state_actions, "r") as f: data = json.load(f) if data[building_ids[0]]["states"][p_key] == p_val: print("Skipping parameter with same value") continue data[building_ids[0]]["states"][p_key] = p_val with open(building_state_actions, "w") as f: json.dump(data, f, indent=4) env = CityLearn(data_path, building_attributes, weather_file, solar_profile, building_ids, buildings_states_actions = building_state_actions, cost_function = objective_function, central_agent = True, verbose = 1) average = 0 for t in range(10): model = SAC(MlpPolicy_SAC, env, verbose=0, learning_rate=0.01, gamma=0.99, tau=3e-4, batch_size=2048, learning_starts=8759) start = time.time() model.learn(total_timesteps=8760*7, log_interval=1000) print("Time: %f" % (time.time()-start)) obs = env.reset() dones = False counter = np.empty(8760) i = 0 while dones==False: action, _states = model.predict(obs) obs, rewards, dones, info = env.step(action) counter[i] = rewards i += 1 average += (np.sum(counter) - average)/(t+1) env.cost() print("") print("Average: %f" % (average)) data[building_ids[0]]["states"][p_key] = not p_val with open(building_state_actions, "w") as f: json.dump(data, f, indent=4) # In[5]: # Plotting winter operation interval = range(0,8759) plt.figure(figsize=(16,5)) plt.plot(env.net_electric_consumption_no_pv_no_storage[interval]) plt.plot(env.net_electric_consumption_no_storage[interval]) plt.plot(env.net_electric_consumption[interval], '--') plt.xlabel('time (hours)') plt.ylabel('kW') plt.legend(['Electricity demand without storage or generation (kW)', 'Electricity demand with PV generation and without storage(kW)', 'Electricity demand with PV generation and using SAC for storage(kW)'])
[ "json.dump", "json.load", "citylearn.CityLearn", "stable_baselines.SAC", "matplotlib.pyplot.plot", "numpy.sum", "numpy.empty", "matplotlib.pyplot.legend", "time.time", "matplotlib.pyplot.figure", "matplotlib.pyplot.ylabel", "matplotlib.pyplot.xlabel" ]
[((2561, 2588), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(16, 5)'}), '(figsize=(16, 5))\n', (2571, 2588), True, 'import matplotlib.pyplot as plt\n'), ((2588, 2653), 'matplotlib.pyplot.plot', 'plt.plot', (['env.net_electric_consumption_no_pv_no_storage[interval]'], {}), '(env.net_electric_consumption_no_pv_no_storage[interval])\n', (2596, 2653), True, 'import matplotlib.pyplot as plt\n'), ((2654, 2713), 'matplotlib.pyplot.plot', 'plt.plot', (['env.net_electric_consumption_no_storage[interval]'], {}), '(env.net_electric_consumption_no_storage[interval])\n', (2662, 2713), True, 'import matplotlib.pyplot as plt\n'), ((2714, 2768), 'matplotlib.pyplot.plot', 'plt.plot', (['env.net_electric_consumption[interval]', '"""--"""'], {}), "(env.net_electric_consumption[interval], '--')\n", (2722, 2768), True, 'import matplotlib.pyplot as plt\n'), ((2769, 2795), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""time (hours)"""'], {}), "('time (hours)')\n", (2779, 2795), True, 'import matplotlib.pyplot as plt\n'), ((2796, 2812), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""kW"""'], {}), "('kW')\n", (2806, 2812), True, 'import matplotlib.pyplot as plt\n'), ((2813, 3026), 'matplotlib.pyplot.legend', 'plt.legend', (["['Electricity demand without storage or generation (kW)',\n 'Electricity demand with PV generation and without storage(kW)',\n 'Electricity demand with PV generation and using SAC for storage(kW)']"], {}), "(['Electricity demand without storage or generation (kW)',\n 'Electricity demand with PV generation and without storage(kW)',\n 'Electricity demand with PV generation and using SAC for storage(kW)'])\n", (2823, 3026), True, 'import matplotlib.pyplot as plt\n'), ((1421, 1627), 'citylearn.CityLearn', 'CityLearn', (['data_path', 'building_attributes', 'weather_file', 'solar_profile', 'building_ids'], {'buildings_states_actions': 'building_state_actions', 'cost_function': 'objective_function', 'central_agent': '(True)', 'verbose': '(1)'}), '(data_path, building_attributes, weather_file, solar_profile,\n building_ids, buildings_states_actions=building_state_actions,\n cost_function=objective_function, central_agent=True, verbose=1)\n', (1430, 1627), False, 'from citylearn import CityLearn\n'), ((1135, 1147), 'json.load', 'json.load', (['f'], {}), '(f)\n', (1144, 1147), False, 'import json\n'), ((1381, 1409), 'json.dump', 'json.dump', (['data', 'f'], {'indent': '(4)'}), '(data, f, indent=4)\n', (1390, 1409), False, 'import json\n'), ((1684, 1806), 'stable_baselines.SAC', 'SAC', (['MlpPolicy_SAC', 'env'], {'verbose': '(0)', 'learning_rate': '(0.01)', 'gamma': '(0.99)', 'tau': '(0.0003)', 'batch_size': '(2048)', 'learning_starts': '(8759)'}), '(MlpPolicy_SAC, env, verbose=0, learning_rate=0.01, gamma=0.99, tau=\n 0.0003, batch_size=2048, learning_starts=8759)\n', (1687, 1806), False, 'from stable_baselines import SAC\n'), ((1816, 1827), 'time.time', 'time.time', ([], {}), '()\n', (1825, 1827), False, 'import time\n'), ((2006, 2020), 'numpy.empty', 'np.empty', (['(8760)'], {}), '(8760)\n', (2014, 2020), True, 'import numpy as np\n'), ((2461, 2489), 'json.dump', 'json.dump', (['data', 'f'], {'indent': '(4)'}), '(data, f, indent=4)\n', (2470, 2489), False, 'import json\n'), ((2241, 2256), 'numpy.sum', 'np.sum', (['counter'], {}), '(counter)\n', (2247, 2256), True, 'import numpy as np\n'), ((1919, 1930), 'time.time', 'time.time', ([], {}), '()\n', (1928, 1930), False, 'import time\n')]
import numpy as np from .loss import Loss from scipy.special import expit class Logistic(Loss): """Single-task Logistic loss. Attributes ---------- x: array-like The features. y: array-like The responses (0/1). w: array-like The observation weights. L: float Hessian upper bound value. mu: float Hessian lower bound value. Methods ------- lin_predictor(beta) Returns the linear predictor evaluated at beta. loss(beta) Returns the loss evaluated at beta. gradient(beta) Returns the gradient evaluated at beta. hessian_upper_bound Returns an upper bound to the Hessian matrix. hessian_lower_bound Returns a lower bound to the Hessian matrix. """ def __init__(self, x: np.ndarray, y: np.ndarray, w: np.ndarray): super().__init__(x, y) self.w = w self.n, self.p = x.shape eig = np.power(np.linalg.svd(self.x * np.sqrt(self.w), compute_uv=False), 2) self.L_ls = np.max(eig) self.L = self.L_ls / 4 self.L_saturated = np.max(self.w) self.mu = np.min(eig) def loss_from_linear_predictor(self, eta): p = expit(eta).clip(1.0e-10, 1. - 1.0e-10) return - np.sum(self.w * (self.y * np.log(p) + (1 - self.y) * np.log(1 - p))) def gradient(self, beta: np.ndarray): return np.matmul(self.x.transpose(), self.gradient_saturated(self.lin_predictor(beta))) def predict(self, beta: np.ndarray): return expit(self.lin_predictor(beta)) def hessian_saturated_upper_bound(self): return self.L_saturated def hessian_ls_upper_bound(self): return self.L_ls def hessian_upper_bound(self): return self.L def hessian_lower_bound(self): return self.mu def gradient_saturated(self, eta: np.ndarray): return - self.w * (self.y - expit(eta))
[ "numpy.log", "scipy.special.expit", "numpy.max", "numpy.min", "numpy.sqrt" ]
[((908, 919), 'numpy.max', 'np.max', (['eig'], {}), '(eig)\n', (914, 919), True, 'import numpy as np\n'), ((966, 980), 'numpy.max', 'np.max', (['self.w'], {}), '(self.w)\n', (972, 980), True, 'import numpy as np\n'), ((993, 1004), 'numpy.min', 'np.min', (['eig'], {}), '(eig)\n', (999, 1004), True, 'import numpy as np\n'), ((1056, 1066), 'scipy.special.expit', 'expit', (['eta'], {}), '(eta)\n', (1061, 1066), False, 'from scipy.special import expit\n'), ((1687, 1697), 'scipy.special.expit', 'expit', (['eta'], {}), '(eta)\n', (1692, 1697), False, 'from scipy.special import expit\n'), ((855, 870), 'numpy.sqrt', 'np.sqrt', (['self.w'], {}), '(self.w)\n', (862, 870), True, 'import numpy as np\n'), ((1132, 1141), 'numpy.log', 'np.log', (['p'], {}), '(p)\n', (1138, 1141), True, 'import numpy as np\n'), ((1159, 1172), 'numpy.log', 'np.log', (['(1 - p)'], {}), '(1 - p)\n', (1165, 1172), True, 'import numpy as np\n')]
# from __future__ import print_function import os import numpy as np import logging import argparse from keras.preprocessing import sequence from keras.utils import np_utils from keras.models import Model from keras.layers import Dense, Dropout, Activation, TimeDistributed, TimeDistributedDense from keras.layers import LSTM, merge, Input from keras.callbacks import ModelCheckpoint, ProgbarLogger, Callback BATCH_SIZE = 500 NUM_EPOCHS = 5 INPUT_DIM = 16 FLOP_DIM = 42 OUTPUT_DIM = 3 INPUT_LENGTH = 20 INTER_DIM = (30, 10) FLOP_INTER_DIM = (30, 20, 10) TRAINING_DATA_DIR = "training_data" TRAIN_DATA_RATIO = 0.75 # Amount of total data to use for training SINGLE_TRAINING_FILENAME = "training_data/training_2.npz" USE_ONE_TRAINING_FILE = False MAX_TRAINING_FILES = 1000 np.random.seed(1337) # for reproducibility logging.basicConfig(format='%(asctime)s %(message)s', level=logging.INFO) class PrintLoss(Callback): def __init__(self, pad_ratio): self.pad_ratio = pad_ratio def on_epoch_end(self, epoch, logs={}): logging.info('True Loss: {0}'.format(logs.get('loss') * self.pad_ratio)) # NUM_SAMPLES / NUM_NON_PADDED_SAMPLES def pad_ratio(y): return float(y.shape[0] * y.shape[1]) / np.sum(y, (0,1,2)) def load_training_data(): logging.info('Loading data...') # Only for testing if USE_ONE_TRAINING_FILE: with open(SINGLE_TRAINING_FILENAME) as f: data = np.load(f) X_train = data["input"] y_train = data["output"] flops_train = data["board"] else: Xs = [] ys = [] flops = [] files = os.listdir(TRAINING_DATA_DIR) np.random.shuffle(files) for i, filename in enumerate(files): if i > MAX_TRAINING_FILES: break full_name = TRAINING_DATA_DIR + "/" + filename with open(full_name) as f: data = np.load(f) if len(data["input"].shape) == 3 and len(data["output"].shape) == 3: Xs.append(data["input"]) ys.append(data["output"]) flops.append(data["board"]) logging.info(str(i)) X_train = np.concatenate(tuple(Xs)) y_train = np.concatenate(tuple(ys)) flops_train = np.concatenate(tuple(flops)) # Expand flops_train flops_train = np.tile(np.expand_dims(flops_train, 1), (1, INPUT_LENGTH, 1)) logging.info("Shape of X_train: ") logging.info(X_train.shape) logging.info("Shape of y_train") logging.info(y_train.shape) logging.info("Shape of flops_train") logging.info(flops_train.shape) # Randomize hands rand_perm = np.random.permutation(X_train.shape[0]) X_train = X_train[rand_perm] y_train = y_train[rand_perm] flops_train = flops_train[rand_perm] train_test_sep_idx = int(X_train.shape[0] * TRAIN_DATA_RATIO) X_test = X_train[train_test_sep_idx:] y_test = y_train[train_test_sep_idx:] X_train = X_train[:train_test_sep_idx] y_train = y_train[:train_test_sep_idx] flops_test = flops_train[train_test_sep_idx:] flops_train = flops_train[:train_test_sep_idx] return X_train, flops_train, y_train, X_test, flops_test, y_test def build_model(processor): logging.info('Build model...') action_input = Input(shape=(INPUT_LENGTH, INPUT_DIM)) actual_flop_input = Input(shape=(INPUT_LENGTH, FLOP_DIM)) flop_input = actual_flop_input # 2 dense layers to encode flop for dim in FLOP_INTER_DIM: flop_input = TimeDistributed(Dense(dim))(flop_input) seq = merge([action_input, flop_input], mode='concat', concat_axis=2) for dim in INTER_DIM: seq = LSTM(dim, return_sequences=True, dropout_W=0.2, dropout_U=0.2, consume_less=processor)(seq) seq = TimeDistributed(Dense(OUTPUT_DIM))(seq) probs = Activation('softmax')(seq) model = Model(input=[action_input, actual_flop_input], output=probs) # try using different optimizers and different optimizer configs model.compile(loss='categorical_crossentropy', optimizer='rmsprop', metrics=['accuracy']) # plot(model, to_file='model.png', show_shapes=True, show_layer_names=True) return model def train(model, X_train, y_train, X_test, y_test, start_weights_file=None): logging.info('Train...') save_weights = ModelCheckpoint('weights.{epoch:02d}.hdf5') logger = ProgbarLogger() printloss = PrintLoss(pad_ratio(y_test)) if start_weights_file: model.load_weights(start_weights_file) model.fit(X_train, y_train, batch_size=BATCH_SIZE, nb_epoch=NUM_EPOCHS, validation_data=(X_test, y_test), callbacks=[save_weights, logger, printloss]) score, acc = model.evaluate(X_test, y_test, batch_size=BATCH_SIZE) # logging.info('Test score: {0}'.format(score)) # logging.info('Test accuracy: {0}'.format(acc)) if __name__ == '__main__': parser = argparse.ArgumentParser(description='Train Poker Predictor.') parser.add_argument('--file', type=str, help='Start training weights.') parser.add_argument('--gpu', const='gpu', default='cpu', nargs="?", help='sum the integers (default: find the max)') parser.add_argument('--batch-size', type=int, help='Batch size') parser.add_argument('--max-training-files', type=int, help='Maximum number of training files to use.') args = parser.parse_args() if args.batch_size: BATCH_SIZE = args.batch_size if args.max_training_files: MAX_TRAINING_FILES = args.max_training_files X_train, flops_train, y_train, X_test, flops_test, y_test = load_training_data() logging.info("Padding ratio (multiply loss by this): ") logging.info(pad_ratio(y_test)) model = build_model(args.gpu) train(model, [X_train, flops_train], y_train, [X_test, flops_test], y_test, start_weights_file=args.file)
[ "numpy.load", "numpy.random.seed", "argparse.ArgumentParser", "logging.basicConfig", "numpy.sum", "keras.callbacks.ModelCheckpoint", "keras.layers.Input", "numpy.random.shuffle", "keras.layers.Activation", "keras.layers.LSTM", "numpy.expand_dims", "keras.models.Model", "logging.info", "ker...
[((777, 797), 'numpy.random.seed', 'np.random.seed', (['(1337)'], {}), '(1337)\n', (791, 797), True, 'import numpy as np\n'), ((822, 895), 'logging.basicConfig', 'logging.basicConfig', ([], {'format': '"""%(asctime)s %(message)s"""', 'level': 'logging.INFO'}), "(format='%(asctime)s %(message)s', level=logging.INFO)\n", (841, 895), False, 'import logging\n'), ((1272, 1303), 'logging.info', 'logging.info', (['"""Loading data..."""'], {}), "('Loading data...')\n", (1284, 1303), False, 'import logging\n'), ((2436, 2470), 'logging.info', 'logging.info', (['"""Shape of X_train: """'], {}), "('Shape of X_train: ')\n", (2448, 2470), False, 'import logging\n'), ((2475, 2502), 'logging.info', 'logging.info', (['X_train.shape'], {}), '(X_train.shape)\n', (2487, 2502), False, 'import logging\n'), ((2507, 2539), 'logging.info', 'logging.info', (['"""Shape of y_train"""'], {}), "('Shape of y_train')\n", (2519, 2539), False, 'import logging\n'), ((2544, 2571), 'logging.info', 'logging.info', (['y_train.shape'], {}), '(y_train.shape)\n', (2556, 2571), False, 'import logging\n'), ((2576, 2612), 'logging.info', 'logging.info', (['"""Shape of flops_train"""'], {}), "('Shape of flops_train')\n", (2588, 2612), False, 'import logging\n'), ((2617, 2648), 'logging.info', 'logging.info', (['flops_train.shape'], {}), '(flops_train.shape)\n', (2629, 2648), False, 'import logging\n'), ((2688, 2727), 'numpy.random.permutation', 'np.random.permutation', (['X_train.shape[0]'], {}), '(X_train.shape[0])\n', (2709, 2727), True, 'import numpy as np\n'), ((3276, 3306), 'logging.info', 'logging.info', (['"""Build model..."""'], {}), "('Build model...')\n", (3288, 3306), False, 'import logging\n'), ((3327, 3365), 'keras.layers.Input', 'Input', ([], {'shape': '(INPUT_LENGTH, INPUT_DIM)'}), '(shape=(INPUT_LENGTH, INPUT_DIM))\n', (3332, 3365), False, 'from keras.layers import LSTM, merge, Input\n'), ((3390, 3427), 'keras.layers.Input', 'Input', ([], {'shape': '(INPUT_LENGTH, FLOP_DIM)'}), '(shape=(INPUT_LENGTH, FLOP_DIM))\n', (3395, 3427), False, 'from keras.layers import LSTM, merge, Input\n'), ((3603, 3666), 'keras.layers.merge', 'merge', (['[action_input, flop_input]'], {'mode': '"""concat"""', 'concat_axis': '(2)'}), "([action_input, flop_input], mode='concat', concat_axis=2)\n", (3608, 3666), False, 'from keras.layers import LSTM, merge, Input\n'), ((3925, 3985), 'keras.models.Model', 'Model', ([], {'input': '[action_input, actual_flop_input]', 'output': 'probs'}), '(input=[action_input, actual_flop_input], output=probs)\n', (3930, 3985), False, 'from keras.models import Model\n'), ((4370, 4394), 'logging.info', 'logging.info', (['"""Train..."""'], {}), "('Train...')\n", (4382, 4394), False, 'import logging\n'), ((4414, 4457), 'keras.callbacks.ModelCheckpoint', 'ModelCheckpoint', (['"""weights.{epoch:02d}.hdf5"""'], {}), "('weights.{epoch:02d}.hdf5')\n", (4429, 4457), False, 'from keras.callbacks import ModelCheckpoint, ProgbarLogger, Callback\n'), ((4471, 4486), 'keras.callbacks.ProgbarLogger', 'ProgbarLogger', ([], {}), '()\n', (4484, 4486), False, 'from keras.callbacks import ModelCheckpoint, ProgbarLogger, Callback\n'), ((5027, 5088), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""Train Poker Predictor."""'}), "(description='Train Poker Predictor.')\n", (5050, 5088), False, 'import argparse\n'), ((5781, 5836), 'logging.info', 'logging.info', (['"""Padding ratio (multiply loss by this): """'], {}), "('Padding ratio (multiply loss by this): ')\n", (5793, 5836), False, 'import logging\n'), ((1222, 1242), 'numpy.sum', 'np.sum', (['y', '(0, 1, 2)'], {}), '(y, (0, 1, 2))\n', (1228, 1242), True, 'import numpy as np\n'), ((1628, 1657), 'os.listdir', 'os.listdir', (['TRAINING_DATA_DIR'], {}), '(TRAINING_DATA_DIR)\n', (1638, 1657), False, 'import os\n'), ((1666, 1690), 'numpy.random.shuffle', 'np.random.shuffle', (['files'], {}), '(files)\n', (1683, 1690), True, 'import numpy as np\n'), ((2377, 2407), 'numpy.expand_dims', 'np.expand_dims', (['flops_train', '(1)'], {}), '(flops_train, 1)\n', (2391, 2407), True, 'import numpy as np\n'), ((3885, 3906), 'keras.layers.Activation', 'Activation', (['"""softmax"""'], {}), "('softmax')\n", (3895, 3906), False, 'from keras.layers import Dense, Dropout, Activation, TimeDistributed, TimeDistributedDense\n'), ((1427, 1437), 'numpy.load', 'np.load', (['f'], {}), '(f)\n', (1434, 1437), True, 'import numpy as np\n'), ((3712, 3803), 'keras.layers.LSTM', 'LSTM', (['dim'], {'return_sequences': '(True)', 'dropout_W': '(0.2)', 'dropout_U': '(0.2)', 'consume_less': 'processor'}), '(dim, return_sequences=True, dropout_W=0.2, dropout_U=0.2, consume_less\n =processor)\n', (3716, 3803), False, 'from keras.layers import LSTM, merge, Input\n'), ((3849, 3866), 'keras.layers.Dense', 'Dense', (['OUTPUT_DIM'], {}), '(OUTPUT_DIM)\n', (3854, 3866), False, 'from keras.layers import Dense, Dropout, Activation, TimeDistributed, TimeDistributedDense\n'), ((1918, 1928), 'numpy.load', 'np.load', (['f'], {}), '(f)\n', (1925, 1928), True, 'import numpy as np\n'), ((3568, 3578), 'keras.layers.Dense', 'Dense', (['dim'], {}), '(dim)\n', (3573, 3578), False, 'from keras.layers import Dense, Dropout, Activation, TimeDistributed, TimeDistributedDense\n')]
from biosimulators_test_suite import utils from biosimulators_test_suite.config import Config import math import numpy import os import unittest class UtilsTestCase(unittest.TestCase): def test_get_singularity_image_filename(self): base_dir = Config().singularity_image_dirname filename = utils.get_singularity_image_filename('ghcr.io/biosimulators/biosimulators_tellurium/tellurium:2.2.0') print(filename) self.assertTrue(os.path.relpath(filename, base_dir).startswith('ghcr.io_')) self.assertTrue(filename.endswith('_2.2.0.sif')) def test_simulation_results_isnan(self): self.assertTrue(utils.simulation_results_isnan(math.nan)) self.assertFalse(utils.simulation_results_isnan(2)) self.assertFalse(utils.simulation_results_isnan(3.)) self.assertTrue(numpy.any(utils.simulation_results_isnan(numpy.array([math.nan])))) self.assertFalse(numpy.any(utils.simulation_results_isnan(numpy.array([3])))) self.assertFalse(numpy.any(utils.simulation_results_isnan(numpy.array([4.])))) with self.assertRaises(TypeError): utils.simulation_results_isnan('a') with self.assertRaises(TypeError): utils.simulation_results_isnan(numpy.array(['a']))
[ "biosimulators_test_suite.utils.simulation_results_isnan", "biosimulators_test_suite.utils.get_singularity_image_filename", "numpy.array", "os.path.relpath", "biosimulators_test_suite.config.Config" ]
[((311, 417), 'biosimulators_test_suite.utils.get_singularity_image_filename', 'utils.get_singularity_image_filename', (['"""ghcr.io/biosimulators/biosimulators_tellurium/tellurium:2.2.0"""'], {}), "(\n 'ghcr.io/biosimulators/biosimulators_tellurium/tellurium:2.2.0')\n", (347, 417), False, 'from biosimulators_test_suite import utils\n'), ((257, 265), 'biosimulators_test_suite.config.Config', 'Config', ([], {}), '()\n', (263, 265), False, 'from biosimulators_test_suite.config import Config\n'), ((648, 688), 'biosimulators_test_suite.utils.simulation_results_isnan', 'utils.simulation_results_isnan', (['math.nan'], {}), '(math.nan)\n', (678, 688), False, 'from biosimulators_test_suite import utils\n'), ((715, 748), 'biosimulators_test_suite.utils.simulation_results_isnan', 'utils.simulation_results_isnan', (['(2)'], {}), '(2)\n', (745, 748), False, 'from biosimulators_test_suite import utils\n'), ((775, 810), 'biosimulators_test_suite.utils.simulation_results_isnan', 'utils.simulation_results_isnan', (['(3.0)'], {}), '(3.0)\n', (805, 810), False, 'from biosimulators_test_suite import utils\n'), ((1133, 1168), 'biosimulators_test_suite.utils.simulation_results_isnan', 'utils.simulation_results_isnan', (['"""a"""'], {}), "('a')\n", (1163, 1168), False, 'from biosimulators_test_suite import utils\n'), ((1255, 1273), 'numpy.array', 'numpy.array', (["['a']"], {}), "(['a'])\n", (1266, 1273), False, 'import numpy\n'), ((461, 496), 'os.path.relpath', 'os.path.relpath', (['filename', 'base_dir'], {}), '(filename, base_dir)\n', (476, 496), False, 'import os\n'), ((877, 900), 'numpy.array', 'numpy.array', (['[math.nan]'], {}), '([math.nan])\n', (888, 900), False, 'import numpy\n'), ((970, 986), 'numpy.array', 'numpy.array', (['[3]'], {}), '([3])\n', (981, 986), False, 'import numpy\n'), ((1056, 1074), 'numpy.array', 'numpy.array', (['[4.0]'], {}), '([4.0])\n', (1067, 1074), False, 'import numpy\n')]
# Copyright (c) 2018, <NAME>. All rights reserved. # # This work is licen sed under the Creative Commons Attribution-NonCommercial # 4.0 International License. To view a copy of this license, visit # http://creativecommons.org/licenses/by-nc/4.0/ or send a letter to # Creative Commons, PO Box 1866, Mountain View, CA 94042, USA. import os import time import numpy as np import tensorflow as tf from tf_model.gan_fingerprint import config from tf_model.gan_fingerprint import tfutil from tf_model.gan_fingerprint import dataset from tf_model.gan_fingerprint import misc from sklearn import metrics from tqdm import tqdm import argparse from sklearn.metrics import recall_score,accuracy_score,precision_score,log_loss,classification_report #---------------------------------------------------------------------------- # Choose the size and contents of the image snapshot grids that are exported # periodically during training. #---------------------------------------------------------------------------- # Just-in-time processing of training images before feeding them to the networks. def process_reals(x, lod, lr_mirror_augment, ud_mirror_augment, drange_data, drange_net): with tf.name_scope('ProcessReals'): with tf.name_scope('DynamicRange'): x = tf.cast(x, tf.float32) x = misc.adjust_dynamic_range(x, drange_data, drange_net) if lr_mirror_augment: with tf.name_scope('MirrorAugment'): s = tf.shape(x) mask = tf.random_uniform([s[0], 1, 1, 1], 0.0, 1.0) mask = tf.tile(mask, [1, s[1], s[2], s[3]]) x = tf.where(mask < 0.5, x, tf.reverse(x, axis=[3])) if ud_mirror_augment: with tf.name_scope('udMirrorAugment'): s = tf.shape(x) mask = tf.random_uniform([s[0], 1, 1, 1], 0.0, 1.0) mask = tf.tile(mask, [1, s[1], s[2], s[3]]) x = tf.where(mask < 0.5, x, tf.reverse(x, axis=[2])) with tf.name_scope('FadeLOD'): # Smooth crossfade between consecutive levels-of-detail. s = tf.shape(x) y = tf.reshape(x, [-1, s[1], s[2]//2, 2, s[3]//2, 2]) y = tf.reduce_mean(y, axis=[3, 5], keepdims=True) y = tf.tile(y, [1, 1, 1, 2, 1, 2]) y = tf.reshape(y, [-1, s[1], s[2], s[3]]) x_fade = tfutil.lerp(x, y, lod - tf.floor(lod)) x_orig = tf.identity(x) with tf.name_scope('UpscaleLOD'): # Upscale to match the expected input/output size of the networks. s = tf.shape(x) factor = tf.cast(2 ** tf.floor(lod), tf.int32) x_fade = tf.reshape(x_fade, [-1, s[1], s[2], 1, s[3], 1]) x_fade = tf.tile(x_fade, [1, 1, 1, factor, 1, factor]) x_fade = tf.reshape(x_fade, [-1, s[1], s[2] * factor, s[3] * factor]) x_orig = tf.reshape(x_orig, [-1, s[1], s[2], 1, s[3], 1]) x_orig = tf.tile(x_orig, [1, 1, 1, factor, 1, factor]) x_orig = tf.reshape(x_orig, [-1, s[1], s[2] * factor, s[3] * factor]) return x_fade, x_orig #---------------------------------------------------------------------------- # Class for evaluating and storing the values of time-varying training parameters. class TrainingSchedule: def __init__( self, cur_nimg, training_set, lod_initial_resolution = 128, # Image resolution used at the beginning. lod_training_kimg = 1500, # Thousands of real images to show before doubling the resolution. lod_transition_kimg = 1500, # Thousands of real images to show when fading in new layers. minibatch_base = 16, # Maximum minibatch size, divided evenly among GPUs. minibatch_dict = {}, # Resolution-specific overrides. max_minibatch_per_gpu = {}, # Resolution-specific maximum minibatch size per GPU. lrate_base = 0.001, # Learning rate for AutoEncoder. lrate_dict = {}, # Resolution-specific overrides. tick_kimg_base = 1, # Default interval of progress snapshots. tick_kimg_dict = {}): # Resolution-specific overrides. # Training phase. self.kimg = cur_nimg / 1000.0 phase_dur = lod_training_kimg + lod_transition_kimg phase_idx = int(np.floor(self.kimg / phase_dur)) if phase_dur > 0 else 0 phase_kimg = self.kimg - phase_idx * phase_dur # Level-of-detail and resolution. self.lod = training_set.resolution_log2 self.lod -= np.floor(np.log2(lod_initial_resolution)) self.lod -= phase_idx if lod_transition_kimg > 0: self.lod -= max(phase_kimg - lod_training_kimg, 0.0) / lod_transition_kimg self.lod = max(self.lod, 0.0) self.resolution = 2 ** (training_set.resolution_log2 - int(np.floor(self.lod))) # Minibatch size. self.minibatch = minibatch_dict.get(self.resolution, minibatch_base) self.minibatch -= self.minibatch % config.num_gpus if self.resolution in max_minibatch_per_gpu: self.minibatch = min(self.minibatch, max_minibatch_per_gpu[self.resolution] * config.num_gpus) # Other parameters. self.lrate = lrate_dict.get(self.resolution, lrate_base) self.tick_kimg = tick_kimg_dict.get(self.resolution, tick_kimg_base) #---------------------------------------------------------------------------- # Main training script. # To run, comment/uncomment appropriate lines in config.py and launch train.py. def train_classifier( smoothing = 0.999, # Exponential running average of encoder weights. minibatch_repeats = 4, # Number of minibatches to run before adjusting training parameters. reset_opt_for_new_lod = True, # Reset optimizer internal state (e.g. Adam moments) when new layers are introduced? total_kimg = 25000, # Total length of the training, measured in thousands of real images. lr_mirror_augment = True, # Enable mirror augment? ud_mirror_augment = False, # Enable up-down mirror augment? drange_net = [-1,1], # Dynamic range used when feeding image data to the networks. image_snapshot_ticks = 10, # How often to export image snapshots? save_tf_graph = False, # Include full TensorFlow computation graph in the tfevents file? save_weight_histograms = False, # Include weight histograms in the tfevents file? epochs = 10, total_val_img = 5000, ): maintenance_start_time = time.time() training_set = dataset.load_dataset(data_dir=config.data_dir, verbose=True, **config.training_set) validation_set = dataset.load_dataset(data_dir=config.data_dir, verbose=True, **config.validation_set) # Construct networks. with tf.device('/gpu:0'): try: network_pkl = misc.locate_network_pkl() resume_kimg, resume_time = misc.resume_kimg_time(network_pkl) print('Loading networks from "%s"...' % network_pkl) EG, D_rec, EGs = misc.load_pkl(network_pkl) except: print('Constructing networks...') resume_kimg = 0.0 resume_time = 0.0 EG = tfutil.Network('EG', num_channels=training_set.shape[0], resolution=training_set.shape[1], label_size=training_set.label_size, **config.EG) D_rec = tfutil.Network('D_rec', num_channels=training_set.shape[0], resolution=training_set.shape[1], **config.D_rec) EGs = EG.clone('EGs') EGs_update_op = EGs.setup_as_moving_average_of(EG, beta=smoothing) EG.print_layers(); D_rec.print_layers() print('Building TensorFlow graph...') with tf.name_scope('Inputs'): lod_in = tf.placeholder(tf.float32, name='lod_in', shape=[]) lrate_in = tf.placeholder(tf.float32, name='lrate_in', shape=[]) minibatch_in = tf.placeholder(tf.int32, name='minibatch_in', shape=[]) minibatch_split = minibatch_in // config.num_gpus reals, labels = training_set.get_minibatch_tf() reals_split = tf.split(reals, config.num_gpus) labels_split = tf.split(labels, config.num_gpus) EG_opt = tfutil.Optimizer(name='TrainEG', learning_rate=lrate_in, **config.EG_opt) D_rec_opt = tfutil.Optimizer(name='TrainD_rec', learning_rate=lrate_in, **config.D_rec_opt) for gpu in range(config.num_gpus): with tf.name_scope('GPU%d' % gpu), tf.device('/gpu:%d' % gpu): EG_gpu = EG if gpu == 0 else EG.clone(EG.name + '_shadow_%d' % gpu) D_rec_gpu = D_rec if gpu == 0 else D_rec.clone(D_rec.name + '_shadow_%d' % gpu) reals_fade_gpu, reals_orig_gpu = process_reals(reals_split[gpu], lod_in, lr_mirror_augment, ud_mirror_augment, training_set.dynamic_range, drange_net) labels_gpu = labels_split[gpu] with tf.name_scope('EG_loss'): EG_loss = tfutil.call_func_by_name(EG=EG_gpu, D_rec=D_rec_gpu, reals_orig=reals_orig_gpu, labels=labels_gpu, **config.EG_loss) with tf.name_scope('D_rec_loss'): D_rec_loss = tfutil.call_func_by_name(EG=EG_gpu, D_rec=D_rec_gpu, D_rec_opt=D_rec_opt, minibatch_size=minibatch_split, reals_orig=reals_orig_gpu, **config.D_rec_loss) EG_opt.register_gradients(tf.reduce_mean(EG_loss), EG_gpu.trainables) D_rec_opt.register_gradients(tf.reduce_mean(D_rec_loss), D_rec_gpu.trainables) EG_train_op = EG_opt.apply_updates() D_rec_train_op = D_rec_opt.apply_updates() print('Setting up result dir...') result_subdir = misc.create_result_subdir(config.result_dir, config.desc) est_fingerprints = np.transpose(EGs.vars['Conv_fingerprints/weight'].eval(), axes=[3,2,0,1]) misc.save_image_grid(est_fingerprints, os.path.join(result_subdir, 'est_fingerrints-init.png'), drange=[np.amin(est_fingerprints), np.amax(est_fingerprints)], grid_size=[est_fingerprints.shape[0],1]) summary_log = tf.summary.FileWriter(result_subdir) if save_tf_graph: summary_log.add_graph(tf.get_default_graph()) if save_weight_histograms: EG.setup_weight_histograms(); D_rec.setup_weight_histograms() print('Training...') cur_nimg = int(resume_kimg * 1000) cur_tick = 0 tick_start_nimg = cur_nimg tick_start_time = time.time() train_start_time = tick_start_time - resume_time prev_lod = -1.0 total_val_iter = int(total_val_img/config.sched.minibatch_base) text_writer = open(os.path.join(config.result_dir, 'train.csv'), 'a') print(int(total_kimg * 1000/config.sched.minibatch_base)) for i in range(epochs): # while cur_nimg < total_kimg * 1000: cur_nimg = 0 for jtrain in tqdm(range(int(total_kimg * 1000/config.sched.minibatch_base))): # Choose training parameters and configure training ops. sched = TrainingSchedule(cur_nimg, training_set, **config.sched) training_set.configure(config.sched.minibatch_base, sched.lod) # if reset_opt_for_new_lod: # if np.floor(sched.lod) != np.floor(prev_lod) or np.ceil(sched.lod) != np.ceil(prev_lod): # EG_opt.reset_optimizer_state(); D_rec_opt.reset_optimizer_state() # prev_lod = sched.lod # Run training ops. for repeat in range(minibatch_repeats): tfutil.run([D_rec_train_op], {lod_in: sched.lod, lrate_in: sched.lrate, minibatch_in: config.sched.minibatch_base}) tfutil.run([EG_train_op], {lod_in: sched.lod, lrate_in: sched.lrate, minibatch_in: config.sched.minibatch_base}) tfutil.run([EGs_update_op], {}) cur_nimg += config.sched.minibatch_base # Perform maintenance tasks once per tick. cur_tick += 1 cur_time = time.time() tick_start_nimg = cur_nimg tick_time = cur_time - tick_start_time total_time = cur_time - train_start_time maintenance_time = tick_start_time - maintenance_start_time maintenance_start_time = cur_time # Report progress. print( 'tick %-5d kimg %-8.1f time %-12s sec/tick %-7.1f maintenance %.1f' % ( tfutil.autosummary('Progress/tick', cur_tick), tfutil.autosummary('Progress/kimg', cur_nimg / 1000.0), misc.format_time(tfutil.autosummary('Timing/total_sec', total_time)), tfutil.autosummary('Timing/sec_per_tick', tick_time), tfutil.autosummary('Timing/maintenance_sec', maintenance_time))) tfutil.autosummary('Timing/total_hours', total_time / (60.0 * 60.0)) tfutil.autosummary('Timing/total_days', total_time / (24.0 * 60.0 * 60.0)) tfutil.save_summaries(summary_log, cur_nimg) y_label = [] y_pred = [] y_pred_label = [] for jtest in range(total_val_iter): real, label = validation_set.get_minibatch_np(config.sched.minibatch_base) real = misc.adjust_dynamic_range(real, training_set.dynamic_range, drange_net) rec, fingerprint, logits = EGs.run(real, minibatch_size=config.sched.minibatch_base, num_gpus=1, out_dtype=np.float32) idx = np.argmax(np.squeeze(logits),axis=1) y_pred_label.extend(idx) y_label.extend(np.argmax(np.squeeze(label), axis=1)) y_pred.extend(logits) # print(logits) # print("438 idx: ", idx) # acc_test = metrics.accuracy_score(idxs, labels) acc_test = np.float32(np.sum(np.array(y_pred_label) == np.array(y_label))) / np.float32(len(y_label)) log_loss_metric = log_loss(y_label, y_pred, labels=np.array([0., 1.])) print("Epoch %d : loss : %f accuracy : %f " %(i,log_loss_metric,acc_test)) text_writer.write("Epoch %d : loss : %f accuracy : %f " %(i,log_loss_metric,acc_test)) text_writer.flush() misc.save_pkl((EG, D_rec, EGs), os.path.join(result_subdir, 'network-snapshot-%06d.pkl' % (i))) # Write final results. misc.save_pkl((EG, D_rec, EGs), os.path.join(result_subdir, 'network-final.pkl')) summary_log.close() open(os.path.join(result_subdir, '_training-done.txt'), 'wt').close() from scipy.special import softmax def eval_classifier( drange_net = [-1,1], # Dynamic range used when feeding image data to the networks. total_val_img = 5000, model_path="checkpoint", show_time=False ): maintenance_start_time = time.time() validation_set = dataset.load_dataset(data_dir=config.data_dir, verbose=True, **config.validation_set) # Construct networks. with tf.device('/gpu:0'): try: EG, D_rec, EGs = misc.load_network_pkl(model_path) print('Loading networks from "%s"...' % model_path) except: print('Khong load duoc model...') return EG.print_layers(); D_rec.print_layers() print('Eval...') total_val_iter = int(total_val_img/config.sched.minibatch_base) y_label = [] y_pred = [] y_pred_label = [] y_softmax = [] begin = time.time() for jtest in range(total_val_iter): #begin = time.time() real, label = validation_set.get_minibatch_np(config.sched.minibatch_base) real = misc.adjust_dynamic_range(real, validation_set.dynamic_range, drange_net) rec, fingerprint, logits = EGs.run(real, minibatch_size=config.sched.minibatch_base, num_gpus=1, out_dtype=np.float32) idx = np.argmax(np.squeeze(logits),axis=1) #if show_time: # print("Time: ",time.time()-begin) y_pred_label.extend(idx) y_label.extend(np.argmax(np.squeeze(label), axis=1)) y_pred.extend(logits) y_softmax.extend(softmax(logits,axis=1)) # print(logits) # print("438 idx: ", idx) # acc_test = metrics.accuracy_score(idxs, labels) if show_time: print("Time: ",time.time()-begin) acc_test = np.float32(np.sum(np.array(y_pred_label) == np.array(y_label))) / np.float32(len(y_label)) log_loss_metric = log_loss(y_label, y_softmax, labels=np.array([0., 1.])) print("loss : %f accuracy : %f " % (log_loss_metric, acc_test)) print(acc_test) print(f"Test log_loss: {log_loss(y_label,y_softmax,labels=np.array([0.,1.])):.3f}\n" + f"Test accuracy_score: {accuracy_score(y_label,y_pred_label):.3f}\n" + f"Test precision_score: {precision_score(y_label,y_pred_label):.3f}\n" + f"Test recall: {recall_score(y_label,y_pred_label):.3f}\n") print(classification_report(y_label,y_pred_label)) #---------------------------------------------------------------------------- # Main entry point. # Calls the function indicated in config.py. if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument('--app', type=str, default=' ') #------------------- training arguments ------------------- parser.add_argument('--training_data_dir', type=str, default=' ') # The prepared training dataset directory that can be efficiently called by the code parser.add_argument('--validation_data_dir', type=str, default=' ') # The prepared validation dataset directory that can be efficiently called by the code parser.add_argument('--out_model_dir', type=str, default=' ') # The output directory containing trained models, training configureation, training log, and training snapshots parser.add_argument('--training_seed', type=int, default=1000) # The random seed that differentiates training instances #------------------- image generation arguments ------------------- parser.add_argument('--model_path', type=str, default=' ') # The pre-trained GAN model parser.add_argument('--testing_data_path', type=str, default=' ') # The path of testing image file or the directory containing a collection of testing images parser.add_argument('--out_fingerprint_dir', type=str, default=' ') # The output directory containing model fingerprints, image fingerprints, and image fingerprints masked(re-weighted) by each model fingerprint args = parser.parse_args() if args.app == 'train': assert args.training_data_dir != ' ' and args.out_model_dir != ' ' if args.validation_data_dir == ' ': args.validation_data_dir = args.training_data_dir misc.init_output_logging() np.random.seed(args.training_seed) print('Initializing TensorFlow...') os.environ.update(config.env) tfutil.init_tf(config.tf_config) if args.training_data_dir[-1] == '/': args.training_data_dir = args.training_data_dir[:-1] idx = args.training_data_dir.rfind('/') config.data_dir = args.training_data_dir[:idx] config.training_set = config.EasyDict(tfrecord_dir=args.training_data_dir[idx+1:], max_label_size='full') if args.validation_data_dir[-1] == '/': args.validation_data_dir = args.validation_data_dir[:-1] idx = args.validation_data_dir.rfind('/') config.validation_set = config.EasyDict(tfrecord_dir=args.validation_data_dir[idx+1:], max_label_size='full') app = config.EasyDict(func='run.train_classifier', lr_mirror_augment=True, ud_mirror_augment=False, total_kimg=25000) config.result_dir = args.out_model_dir elif args.app == 'test': assert args.model_path != ' ' and args.testing_data_path != ' ' and args.out_fingerprint_dir != ' ' misc.init_output_logging() print('Initializing TensorFlow...') os.environ.update(config.env) tfutil.init_tf(config.tf_config) app = config.EasyDict(func='util_scripts.classify', model_path=args.model_path, testing_data_path=args.testing_data_path, out_fingerprint_dir=args.out_fingerprint_dir) tfutil.call_func_by_name(**app)
[ "tf_model.gan_fingerprint.misc.create_result_subdir", "argparse.ArgumentParser", "numpy.random.seed", "tf_model.gan_fingerprint.tfutil.save_summaries", "tensorflow.identity", "tf_model.gan_fingerprint.tfutil.Network", "numpy.floor", "tensorflow.reshape", "tf_model.gan_fingerprint.tfutil.init_tf", ...
[((6721, 6732), 'time.time', 'time.time', ([], {}), '()\n', (6730, 6732), False, 'import time\n'), ((6752, 6840), 'tf_model.gan_fingerprint.dataset.load_dataset', 'dataset.load_dataset', ([], {'data_dir': 'config.data_dir', 'verbose': '(True)'}), '(data_dir=config.data_dir, verbose=True, **config.\n training_set)\n', (6772, 6840), False, 'from tf_model.gan_fingerprint import dataset\n'), ((6857, 6947), 'tf_model.gan_fingerprint.dataset.load_dataset', 'dataset.load_dataset', ([], {'data_dir': 'config.data_dir', 'verbose': '(True)'}), '(data_dir=config.data_dir, verbose=True, **config.\n validation_set)\n', (6877, 6947), False, 'from tf_model.gan_fingerprint import dataset\n'), ((8387, 8460), 'tf_model.gan_fingerprint.tfutil.Optimizer', 'tfutil.Optimizer', ([], {'name': '"""TrainEG"""', 'learning_rate': 'lrate_in'}), "(name='TrainEG', learning_rate=lrate_in, **config.EG_opt)\n", (8403, 8460), False, 'from tf_model.gan_fingerprint import tfutil\n'), ((8477, 8556), 'tf_model.gan_fingerprint.tfutil.Optimizer', 'tfutil.Optimizer', ([], {'name': '"""TrainD_rec"""', 'learning_rate': 'lrate_in'}), "(name='TrainD_rec', learning_rate=lrate_in, **config.D_rec_opt)\n", (8493, 8556), False, 'from tf_model.gan_fingerprint import tfutil\n'), ((9780, 9837), 'tf_model.gan_fingerprint.misc.create_result_subdir', 'misc.create_result_subdir', (['config.result_dir', 'config.desc'], {}), '(config.result_dir, config.desc)\n', (9805, 9837), False, 'from tf_model.gan_fingerprint import misc\n'), ((10159, 10195), 'tensorflow.summary.FileWriter', 'tf.summary.FileWriter', (['result_subdir'], {}), '(result_subdir)\n', (10180, 10195), True, 'import tensorflow as tf\n'), ((10508, 10519), 'time.time', 'time.time', ([], {}), '()\n', (10517, 10519), False, 'import time\n'), ((14736, 14747), 'time.time', 'time.time', ([], {}), '()\n', (14745, 14747), False, 'import time\n'), ((14769, 14859), 'tf_model.gan_fingerprint.dataset.load_dataset', 'dataset.load_dataset', ([], {'data_dir': 'config.data_dir', 'verbose': '(True)'}), '(data_dir=config.data_dir, verbose=True, **config.\n validation_set)\n', (14789, 14859), False, 'from tf_model.gan_fingerprint import dataset\n'), ((15355, 15366), 'time.time', 'time.time', ([], {}), '()\n', (15364, 15366), False, 'import time\n'), ((17042, 17067), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (17065, 17067), False, 'import argparse\n'), ((20052, 20083), 'tf_model.gan_fingerprint.tfutil.call_func_by_name', 'tfutil.call_func_by_name', ([], {}), '(**app)\n', (20076, 20083), False, 'from tf_model.gan_fingerprint import tfutil\n'), ((1190, 1219), 'tensorflow.name_scope', 'tf.name_scope', (['"""ProcessReals"""'], {}), "('ProcessReals')\n", (1203, 1219), True, 'import tensorflow as tf\n'), ((6979, 6998), 'tensorflow.device', 'tf.device', (['"""/gpu:0"""'], {}), "('/gpu:0')\n", (6988, 6998), True, 'import tensorflow as tf\n'), ((7874, 7897), 'tensorflow.name_scope', 'tf.name_scope', (['"""Inputs"""'], {}), "('Inputs')\n", (7887, 7897), True, 'import tensorflow as tf\n'), ((7925, 7976), 'tensorflow.placeholder', 'tf.placeholder', (['tf.float32'], {'name': '"""lod_in"""', 'shape': '[]'}), "(tf.float32, name='lod_in', shape=[])\n", (7939, 7976), True, 'import tensorflow as tf\n'), ((8003, 8056), 'tensorflow.placeholder', 'tf.placeholder', (['tf.float32'], {'name': '"""lrate_in"""', 'shape': '[]'}), "(tf.float32, name='lrate_in', shape=[])\n", (8017, 8056), True, 'import tensorflow as tf\n'), ((8083, 8138), 'tensorflow.placeholder', 'tf.placeholder', (['tf.int32'], {'name': '"""minibatch_in"""', 'shape': '[]'}), "(tf.int32, name='minibatch_in', shape=[])\n", (8097, 8138), True, 'import tensorflow as tf\n'), ((8281, 8313), 'tensorflow.split', 'tf.split', (['reals', 'config.num_gpus'], {}), '(reals, config.num_gpus)\n', (8289, 8313), True, 'import tensorflow as tf\n'), ((8340, 8373), 'tensorflow.split', 'tf.split', (['labels', 'config.num_gpus'], {}), '(labels, config.num_gpus)\n', (8348, 8373), True, 'import tensorflow as tf\n'), ((9979, 10034), 'os.path.join', 'os.path.join', (['result_subdir', '"""est_fingerrints-init.png"""'], {}), "(result_subdir, 'est_fingerrints-init.png')\n", (9991, 10034), False, 'import os\n'), ((10684, 10728), 'os.path.join', 'os.path.join', (['config.result_dir', '"""train.csv"""'], {}), "(config.result_dir, 'train.csv')\n", (10696, 10728), False, 'import os\n'), ((12010, 12021), 'time.time', 'time.time', ([], {}), '()\n', (12019, 12021), False, 'import time\n'), ((12770, 12838), 'tf_model.gan_fingerprint.tfutil.autosummary', 'tfutil.autosummary', (['"""Timing/total_hours"""', '(total_time / (60.0 * 60.0))'], {}), "('Timing/total_hours', total_time / (60.0 * 60.0))\n", (12788, 12838), False, 'from tf_model.gan_fingerprint import tfutil\n'), ((12847, 12921), 'tf_model.gan_fingerprint.tfutil.autosummary', 'tfutil.autosummary', (['"""Timing/total_days"""', '(total_time / (24.0 * 60.0 * 60.0))'], {}), "('Timing/total_days', total_time / (24.0 * 60.0 * 60.0))\n", (12865, 12921), False, 'from tf_model.gan_fingerprint import tfutil\n'), ((12930, 12974), 'tf_model.gan_fingerprint.tfutil.save_summaries', 'tfutil.save_summaries', (['summary_log', 'cur_nimg'], {}), '(summary_log, cur_nimg)\n', (12951, 12974), False, 'from tf_model.gan_fingerprint import tfutil\n'), ((14304, 14352), 'os.path.join', 'os.path.join', (['result_subdir', '"""network-final.pkl"""'], {}), "(result_subdir, 'network-final.pkl')\n", (14316, 14352), False, 'import os\n'), ((14891, 14910), 'tensorflow.device', 'tf.device', (['"""/gpu:0"""'], {}), "('/gpu:0')\n", (14900, 14910), True, 'import tensorflow as tf\n'), ((15534, 15607), 'tf_model.gan_fingerprint.misc.adjust_dynamic_range', 'misc.adjust_dynamic_range', (['real', 'validation_set.dynamic_range', 'drange_net'], {}), '(real, validation_set.dynamic_range, drange_net)\n', (15559, 15607), False, 'from tf_model.gan_fingerprint import misc\n'), ((16812, 16856), 'sklearn.metrics.classification_report', 'classification_report', (['y_label', 'y_pred_label'], {}), '(y_label, y_pred_label)\n', (16833, 16856), False, 'from sklearn.metrics import recall_score, accuracy_score, precision_score, log_loss, classification_report\n'), ((18593, 18619), 'tf_model.gan_fingerprint.misc.init_output_logging', 'misc.init_output_logging', ([], {}), '()\n', (18617, 18619), False, 'from tf_model.gan_fingerprint import misc\n'), ((18628, 18662), 'numpy.random.seed', 'np.random.seed', (['args.training_seed'], {}), '(args.training_seed)\n', (18642, 18662), True, 'import numpy as np\n'), ((18715, 18744), 'os.environ.update', 'os.environ.update', (['config.env'], {}), '(config.env)\n', (18732, 18744), False, 'import os\n'), ((18753, 18785), 'tf_model.gan_fingerprint.tfutil.init_tf', 'tfutil.init_tf', (['config.tf_config'], {}), '(config.tf_config)\n', (18767, 18785), False, 'from tf_model.gan_fingerprint import tfutil\n'), ((19030, 19119), 'tf_model.gan_fingerprint.config.EasyDict', 'config.EasyDict', ([], {'tfrecord_dir': 'args.training_data_dir[idx + 1:]', 'max_label_size': '"""full"""'}), "(tfrecord_dir=args.training_data_dir[idx + 1:],\n max_label_size='full')\n", (19045, 19119), False, 'from tf_model.gan_fingerprint import config\n'), ((19313, 19404), 'tf_model.gan_fingerprint.config.EasyDict', 'config.EasyDict', ([], {'tfrecord_dir': 'args.validation_data_dir[idx + 1:]', 'max_label_size': '"""full"""'}), "(tfrecord_dir=args.validation_data_dir[idx + 1:],\n max_label_size='full')\n", (19328, 19404), False, 'from tf_model.gan_fingerprint import config\n'), ((19413, 19528), 'tf_model.gan_fingerprint.config.EasyDict', 'config.EasyDict', ([], {'func': '"""run.train_classifier"""', 'lr_mirror_augment': '(True)', 'ud_mirror_augment': '(False)', 'total_kimg': '(25000)'}), "(func='run.train_classifier', lr_mirror_augment=True,\n ud_mirror_augment=False, total_kimg=25000)\n", (19428, 19528), False, 'from tf_model.gan_fingerprint import config\n'), ((1234, 1263), 'tensorflow.name_scope', 'tf.name_scope', (['"""DynamicRange"""'], {}), "('DynamicRange')\n", (1247, 1263), True, 'import tensorflow as tf\n'), ((1281, 1303), 'tensorflow.cast', 'tf.cast', (['x', 'tf.float32'], {}), '(x, tf.float32)\n', (1288, 1303), True, 'import tensorflow as tf\n'), ((1320, 1373), 'tf_model.gan_fingerprint.misc.adjust_dynamic_range', 'misc.adjust_dynamic_range', (['x', 'drange_data', 'drange_net'], {}), '(x, drange_data, drange_net)\n', (1345, 1373), False, 'from tf_model.gan_fingerprint import misc\n'), ((2005, 2029), 'tensorflow.name_scope', 'tf.name_scope', (['"""FadeLOD"""'], {}), "('FadeLOD')\n", (2018, 2029), True, 'import tensorflow as tf\n'), ((2104, 2115), 'tensorflow.shape', 'tf.shape', (['x'], {}), '(x)\n', (2112, 2115), True, 'import tensorflow as tf\n'), ((2132, 2185), 'tensorflow.reshape', 'tf.reshape', (['x', '[-1, s[1], s[2] // 2, 2, s[3] // 2, 2]'], {}), '(x, [-1, s[1], s[2] // 2, 2, s[3] // 2, 2])\n', (2142, 2185), True, 'import tensorflow as tf\n'), ((2198, 2243), 'tensorflow.reduce_mean', 'tf.reduce_mean', (['y'], {'axis': '[3, 5]', 'keepdims': '(True)'}), '(y, axis=[3, 5], keepdims=True)\n', (2212, 2243), True, 'import tensorflow as tf\n'), ((2260, 2290), 'tensorflow.tile', 'tf.tile', (['y', '[1, 1, 1, 2, 1, 2]'], {}), '(y, [1, 1, 1, 2, 1, 2])\n', (2267, 2290), True, 'import tensorflow as tf\n'), ((2307, 2344), 'tensorflow.reshape', 'tf.reshape', (['y', '[-1, s[1], s[2], s[3]]'], {}), '(y, [-1, s[1], s[2], s[3]])\n', (2317, 2344), True, 'import tensorflow as tf\n'), ((2426, 2440), 'tensorflow.identity', 'tf.identity', (['x'], {}), '(x)\n', (2437, 2440), True, 'import tensorflow as tf\n'), ((2454, 2481), 'tensorflow.name_scope', 'tf.name_scope', (['"""UpscaleLOD"""'], {}), "('UpscaleLOD')\n", (2467, 2481), True, 'import tensorflow as tf\n'), ((2566, 2577), 'tensorflow.shape', 'tf.shape', (['x'], {}), '(x)\n', (2574, 2577), True, 'import tensorflow as tf\n'), ((2658, 2706), 'tensorflow.reshape', 'tf.reshape', (['x_fade', '[-1, s[1], s[2], 1, s[3], 1]'], {}), '(x_fade, [-1, s[1], s[2], 1, s[3], 1])\n', (2668, 2706), True, 'import tensorflow as tf\n'), ((2728, 2773), 'tensorflow.tile', 'tf.tile', (['x_fade', '[1, 1, 1, factor, 1, factor]'], {}), '(x_fade, [1, 1, 1, factor, 1, factor])\n', (2735, 2773), True, 'import tensorflow as tf\n'), ((2795, 2855), 'tensorflow.reshape', 'tf.reshape', (['x_fade', '[-1, s[1], s[2] * factor, s[3] * factor]'], {}), '(x_fade, [-1, s[1], s[2] * factor, s[3] * factor])\n', (2805, 2855), True, 'import tensorflow as tf\n'), ((2877, 2925), 'tensorflow.reshape', 'tf.reshape', (['x_orig', '[-1, s[1], s[2], 1, s[3], 1]'], {}), '(x_orig, [-1, s[1], s[2], 1, s[3], 1])\n', (2887, 2925), True, 'import tensorflow as tf\n'), ((2947, 2992), 'tensorflow.tile', 'tf.tile', (['x_orig', '[1, 1, 1, factor, 1, factor]'], {}), '(x_orig, [1, 1, 1, factor, 1, factor])\n', (2954, 2992), True, 'import tensorflow as tf\n'), ((3014, 3074), 'tensorflow.reshape', 'tf.reshape', (['x_orig', '[-1, s[1], s[2] * factor, s[3] * factor]'], {}), '(x_orig, [-1, s[1], s[2] * factor, s[3] * factor])\n', (3024, 3074), True, 'import tensorflow as tf\n'), ((4639, 4670), 'numpy.log2', 'np.log2', (['lod_initial_resolution'], {}), '(lod_initial_resolution)\n', (4646, 4670), True, 'import numpy as np\n'), ((7039, 7064), 'tf_model.gan_fingerprint.misc.locate_network_pkl', 'misc.locate_network_pkl', ([], {}), '()\n', (7062, 7064), False, 'from tf_model.gan_fingerprint import misc\n'), ((7104, 7138), 'tf_model.gan_fingerprint.misc.resume_kimg_time', 'misc.resume_kimg_time', (['network_pkl'], {}), '(network_pkl)\n', (7125, 7138), False, 'from tf_model.gan_fingerprint import misc\n'), ((7233, 7259), 'tf_model.gan_fingerprint.misc.load_pkl', 'misc.load_pkl', (['network_pkl'], {}), '(network_pkl)\n', (7246, 7259), False, 'from tf_model.gan_fingerprint import misc\n'), ((8609, 8637), 'tensorflow.name_scope', 'tf.name_scope', (["('GPU%d' % gpu)"], {}), "('GPU%d' % gpu)\n", (8622, 8637), True, 'import tensorflow as tf\n'), ((8639, 8665), 'tensorflow.device', 'tf.device', (["('/gpu:%d' % gpu)"], {}), "('/gpu:%d' % gpu)\n", (8648, 8665), True, 'import tensorflow as tf\n'), ((10248, 10270), 'tensorflow.get_default_graph', 'tf.get_default_graph', ([], {}), '()\n', (10268, 10270), True, 'import tensorflow as tf\n'), ((13193, 13264), 'tf_model.gan_fingerprint.misc.adjust_dynamic_range', 'misc.adjust_dynamic_range', (['real', 'training_set.dynamic_range', 'drange_net'], {}), '(real, training_set.dynamic_range, drange_net)\n', (13218, 13264), False, 'from tf_model.gan_fingerprint import misc\n'), ((14176, 14236), 'os.path.join', 'os.path.join', (['result_subdir', "('network-snapshot-%06d.pkl' % i)"], {}), "(result_subdir, 'network-snapshot-%06d.pkl' % i)\n", (14188, 14236), False, 'import os\n'), ((14954, 14987), 'tf_model.gan_fingerprint.misc.load_network_pkl', 'misc.load_network_pkl', (['model_path'], {}), '(model_path)\n', (14975, 14987), False, 'from tf_model.gan_fingerprint import misc\n'), ((15759, 15777), 'numpy.squeeze', 'np.squeeze', (['logits'], {}), '(logits)\n', (15769, 15777), True, 'import numpy as np\n'), ((16006, 16029), 'scipy.special.softmax', 'softmax', (['logits'], {'axis': '(1)'}), '(logits, axis=1)\n', (16013, 16029), False, 'from scipy.special import softmax\n'), ((16367, 16387), 'numpy.array', 'np.array', (['[0.0, 1.0]'], {}), '([0.0, 1.0])\n', (16375, 16387), True, 'import numpy as np\n'), ((19717, 19743), 'tf_model.gan_fingerprint.misc.init_output_logging', 'misc.init_output_logging', ([], {}), '()\n', (19741, 19743), False, 'from tf_model.gan_fingerprint import misc\n'), ((19796, 19825), 'os.environ.update', 'os.environ.update', (['config.env'], {}), '(config.env)\n', (19813, 19825), False, 'import os\n'), ((19834, 19866), 'tf_model.gan_fingerprint.tfutil.init_tf', 'tfutil.init_tf', (['config.tf_config'], {}), '(config.tf_config)\n', (19848, 19866), False, 'from tf_model.gan_fingerprint import tfutil\n'), ((19881, 20051), 'tf_model.gan_fingerprint.config.EasyDict', 'config.EasyDict', ([], {'func': '"""util_scripts.classify"""', 'model_path': 'args.model_path', 'testing_data_path': 'args.testing_data_path', 'out_fingerprint_dir': 'args.out_fingerprint_dir'}), "(func='util_scripts.classify', model_path=args.model_path,\n testing_data_path=args.testing_data_path, out_fingerprint_dir=args.\n out_fingerprint_dir)\n", (19896, 20051), False, 'from tf_model.gan_fingerprint import config\n'), ((1421, 1451), 'tensorflow.name_scope', 'tf.name_scope', (['"""MirrorAugment"""'], {}), "('MirrorAugment')\n", (1434, 1451), True, 'import tensorflow as tf\n'), ((1473, 1484), 'tensorflow.shape', 'tf.shape', (['x'], {}), '(x)\n', (1481, 1484), True, 'import tensorflow as tf\n'), ((1508, 1552), 'tensorflow.random_uniform', 'tf.random_uniform', (['[s[0], 1, 1, 1]', '(0.0)', '(1.0)'], {}), '([s[0], 1, 1, 1], 0.0, 1.0)\n', (1525, 1552), True, 'import tensorflow as tf\n'), ((1576, 1612), 'tensorflow.tile', 'tf.tile', (['mask', '[1, s[1], s[2], s[3]]'], {}), '(mask, [1, s[1], s[2], s[3]])\n', (1583, 1612), True, 'import tensorflow as tf\n'), ((1729, 1761), 'tensorflow.name_scope', 'tf.name_scope', (['"""udMirrorAugment"""'], {}), "('udMirrorAugment')\n", (1742, 1761), True, 'import tensorflow as tf\n'), ((1783, 1794), 'tensorflow.shape', 'tf.shape', (['x'], {}), '(x)\n', (1791, 1794), True, 'import tensorflow as tf\n'), ((1818, 1862), 'tensorflow.random_uniform', 'tf.random_uniform', (['[s[0], 1, 1, 1]', '(0.0)', '(1.0)'], {}), '([s[0], 1, 1, 1], 0.0, 1.0)\n', (1835, 1862), True, 'import tensorflow as tf\n'), ((1886, 1922), 'tensorflow.tile', 'tf.tile', (['mask', '[1, s[1], s[2], s[3]]'], {}), '(mask, [1, s[1], s[2], s[3]])\n', (1893, 1922), True, 'import tensorflow as tf\n'), ((4407, 4438), 'numpy.floor', 'np.floor', (['(self.kimg / phase_dur)'], {}), '(self.kimg / phase_dur)\n', (4415, 4438), True, 'import numpy as np\n'), ((7399, 7543), 'tf_model.gan_fingerprint.tfutil.Network', 'tfutil.Network', (['"""EG"""'], {'num_channels': 'training_set.shape[0]', 'resolution': 'training_set.shape[1]', 'label_size': 'training_set.label_size'}), "('EG', num_channels=training_set.shape[0], resolution=\n training_set.shape[1], label_size=training_set.label_size, **config.EG)\n", (7413, 7543), False, 'from tf_model.gan_fingerprint import tfutil\n'), ((7559, 7673), 'tf_model.gan_fingerprint.tfutil.Network', 'tfutil.Network', (['"""D_rec"""'], {'num_channels': 'training_set.shape[0]', 'resolution': 'training_set.shape[1]'}), "('D_rec', num_channels=training_set.shape[0], resolution=\n training_set.shape[1], **config.D_rec)\n", (7573, 7673), False, 'from tf_model.gan_fingerprint import tfutil\n'), ((9062, 9086), 'tensorflow.name_scope', 'tf.name_scope', (['"""EG_loss"""'], {}), "('EG_loss')\n", (9075, 9086), True, 'import tensorflow as tf\n'), ((9114, 9235), 'tf_model.gan_fingerprint.tfutil.call_func_by_name', 'tfutil.call_func_by_name', ([], {'EG': 'EG_gpu', 'D_rec': 'D_rec_gpu', 'reals_orig': 'reals_orig_gpu', 'labels': 'labels_gpu'}), '(EG=EG_gpu, D_rec=D_rec_gpu, reals_orig=\n reals_orig_gpu, labels=labels_gpu, **config.EG_loss)\n', (9138, 9235), False, 'from tf_model.gan_fingerprint import tfutil\n'), ((9248, 9275), 'tensorflow.name_scope', 'tf.name_scope', (['"""D_rec_loss"""'], {}), "('D_rec_loss')\n", (9261, 9275), True, 'import tensorflow as tf\n'), ((9306, 9468), 'tf_model.gan_fingerprint.tfutil.call_func_by_name', 'tfutil.call_func_by_name', ([], {'EG': 'EG_gpu', 'D_rec': 'D_rec_gpu', 'D_rec_opt': 'D_rec_opt', 'minibatch_size': 'minibatch_split', 'reals_orig': 'reals_orig_gpu'}), '(EG=EG_gpu, D_rec=D_rec_gpu, D_rec_opt=D_rec_opt,\n minibatch_size=minibatch_split, reals_orig=reals_orig_gpu, **config.\n D_rec_loss)\n', (9330, 9468), False, 'from tf_model.gan_fingerprint import tfutil\n'), ((9498, 9521), 'tensorflow.reduce_mean', 'tf.reduce_mean', (['EG_loss'], {}), '(EG_loss)\n', (9512, 9521), True, 'import tensorflow as tf\n'), ((9583, 9609), 'tensorflow.reduce_mean', 'tf.reduce_mean', (['D_rec_loss'], {}), '(D_rec_loss)\n', (9597, 9609), True, 'import tensorflow as tf\n'), ((10044, 10069), 'numpy.amin', 'np.amin', (['est_fingerprints'], {}), '(est_fingerprints)\n', (10051, 10069), True, 'import numpy as np\n'), ((10071, 10096), 'numpy.amax', 'np.amax', (['est_fingerprints'], {}), '(est_fingerprints)\n', (10078, 10096), True, 'import numpy as np\n'), ((11572, 11691), 'tf_model.gan_fingerprint.tfutil.run', 'tfutil.run', (['[D_rec_train_op]', '{lod_in: sched.lod, lrate_in: sched.lrate, minibatch_in: config.sched.\n minibatch_base}'], {}), '([D_rec_train_op], {lod_in: sched.lod, lrate_in: sched.lrate,\n minibatch_in: config.sched.minibatch_base})\n', (11582, 11691), False, 'from tf_model.gan_fingerprint import tfutil\n'), ((11704, 11820), 'tf_model.gan_fingerprint.tfutil.run', 'tfutil.run', (['[EG_train_op]', '{lod_in: sched.lod, lrate_in: sched.lrate, minibatch_in: config.sched.\n minibatch_base}'], {}), '([EG_train_op], {lod_in: sched.lod, lrate_in: sched.lrate,\n minibatch_in: config.sched.minibatch_base})\n', (11714, 11820), False, 'from tf_model.gan_fingerprint import tfutil\n'), ((11833, 11864), 'tf_model.gan_fingerprint.tfutil.run', 'tfutil.run', (['[EGs_update_op]', '{}'], {}), '([EGs_update_op], {})\n', (11843, 11864), False, 'from tf_model.gan_fingerprint import tfutil\n'), ((13424, 13442), 'numpy.squeeze', 'np.squeeze', (['logits'], {}), '(logits)\n', (13434, 13442), True, 'import numpy as np\n'), ((13880, 13900), 'numpy.array', 'np.array', (['[0.0, 1.0]'], {}), '([0.0, 1.0])\n', (13888, 13900), True, 'import numpy as np\n'), ((14387, 14436), 'os.path.join', 'os.path.join', (['result_subdir', '"""_training-done.txt"""'], {}), "(result_subdir, '_training-done.txt')\n", (14399, 14436), False, 'import os\n'), ((15923, 15940), 'numpy.squeeze', 'np.squeeze', (['label'], {}), '(label)\n', (15933, 15940), True, 'import numpy as np\n'), ((16184, 16195), 'time.time', 'time.time', ([], {}), '()\n', (16193, 16195), False, 'import time\n'), ((1657, 1680), 'tensorflow.reverse', 'tf.reverse', (['x'], {'axis': '[3]'}), '(x, axis=[3])\n', (1667, 1680), True, 'import tensorflow as tf\n'), ((1967, 1990), 'tensorflow.reverse', 'tf.reverse', (['x'], {'axis': '[2]'}), '(x, axis=[2])\n', (1977, 1990), True, 'import tensorflow as tf\n'), ((2390, 2403), 'tensorflow.floor', 'tf.floor', (['lod'], {}), '(lod)\n', (2398, 2403), True, 'import tensorflow as tf\n'), ((2612, 2625), 'tensorflow.floor', 'tf.floor', (['lod'], {}), '(lod)\n', (2620, 2625), True, 'import tensorflow as tf\n'), ((4930, 4948), 'numpy.floor', 'np.floor', (['self.lod'], {}), '(self.lod)\n', (4938, 4948), True, 'import numpy as np\n'), ((12406, 12451), 'tf_model.gan_fingerprint.tfutil.autosummary', 'tfutil.autosummary', (['"""Progress/tick"""', 'cur_tick'], {}), "('Progress/tick', cur_tick)\n", (12424, 12451), False, 'from tf_model.gan_fingerprint import tfutil\n'), ((12469, 12523), 'tf_model.gan_fingerprint.tfutil.autosummary', 'tfutil.autosummary', (['"""Progress/kimg"""', '(cur_nimg / 1000.0)'], {}), "('Progress/kimg', cur_nimg / 1000.0)\n", (12487, 12523), False, 'from tf_model.gan_fingerprint import tfutil\n'), ((12627, 12679), 'tf_model.gan_fingerprint.tfutil.autosummary', 'tfutil.autosummary', (['"""Timing/sec_per_tick"""', 'tick_time'], {}), "('Timing/sec_per_tick', tick_time)\n", (12645, 12679), False, 'from tf_model.gan_fingerprint import tfutil\n'), ((12697, 12759), 'tf_model.gan_fingerprint.tfutil.autosummary', 'tfutil.autosummary', (['"""Timing/maintenance_sec"""', 'maintenance_time'], {}), "('Timing/maintenance_sec', maintenance_time)\n", (12715, 12759), False, 'from tf_model.gan_fingerprint import tfutil\n'), ((13525, 13542), 'numpy.squeeze', 'np.squeeze', (['label'], {}), '(label)\n', (13535, 13542), True, 'import numpy as np\n'), ((16236, 16258), 'numpy.array', 'np.array', (['y_pred_label'], {}), '(y_pred_label)\n', (16244, 16258), True, 'import numpy as np\n'), ((16262, 16279), 'numpy.array', 'np.array', (['y_label'], {}), '(y_label)\n', (16270, 16279), True, 'import numpy as np\n'), ((16758, 16793), 'sklearn.metrics.recall_score', 'recall_score', (['y_label', 'y_pred_label'], {}), '(y_label, y_pred_label)\n', (16770, 16793), False, 'from sklearn.metrics import recall_score, accuracy_score, precision_score, log_loss, classification_report\n'), ((12558, 12608), 'tf_model.gan_fingerprint.tfutil.autosummary', 'tfutil.autosummary', (['"""Timing/total_sec"""', 'total_time'], {}), "('Timing/total_sec', total_time)\n", (12576, 12608), False, 'from tf_model.gan_fingerprint import tfutil\n'), ((13748, 13770), 'numpy.array', 'np.array', (['y_pred_label'], {}), '(y_pred_label)\n', (13756, 13770), True, 'import numpy as np\n'), ((13774, 13791), 'numpy.array', 'np.array', (['y_label'], {}), '(y_label)\n', (13782, 13791), True, 'import numpy as np\n'), ((16684, 16722), 'sklearn.metrics.precision_score', 'precision_score', (['y_label', 'y_pred_label'], {}), '(y_label, y_pred_label)\n', (16699, 16722), False, 'from sklearn.metrics import recall_score, accuracy_score, precision_score, log_loss, classification_report\n'), ((16602, 16639), 'sklearn.metrics.accuracy_score', 'accuracy_score', (['y_label', 'y_pred_label'], {}), '(y_label, y_pred_label)\n', (16616, 16639), False, 'from sklearn.metrics import recall_score, accuracy_score, precision_score, log_loss, classification_report\n'), ((16539, 16559), 'numpy.array', 'np.array', (['[0.0, 1.0]'], {}), '([0.0, 1.0])\n', (16547, 16559), True, 'import numpy as np\n')]
import os import numpy as np import cv2 as cv import time from PIL import Image BODY_PARTS = { "Head": 0, "Neck": 1, "RShoulder": 2, "RElbow": 3, "RWrist": 4, "LShoulder": 5, "LElbow": 6, "LWrist": 7, "RHip": 8, "RKnee": 9, "RAnkle": 10, "LHip": 11, "LKnee": 12, "LAnkle": 13, "Chest": 14, "Background": 15} POSE_PAIRS = [["Head", "Neck"], ["Neck", "RShoulder"], ["RShoulder", "RElbow"], ["RElbow", "RWrist"], ["Neck", "LShoulder"], ["LShoulder", "LElbow"], ["LElbow", "LWrist"], ["Neck", "Chest"], ["Chest", "RHip"], ["RHip", "RKnee"], ["RKnee", "RAnkle"], ["Chest", "LHip"], ["LHip", "LKnee"], ["LKnee", "LAnkle"]] inWidth = 368 inHeight = 368 thr = 0.1 proto = 'pose/mpi/pose_deploy_linevec_faster_4_stages.prototxt' model = 'pose/mpi/pose_iter_160000.caffemodel' net = cv.dnn.readNetFromCaffe(proto, model) image_dir = 'bikini_data' success = 0 falt = 0 for input in os.listdir(image_dir): frame = cv.imread(image_dir + '/' + input) frameWidth = frame.shape[1] frameHeight = frame.shape[0] inp = cv.dnn.blobFromImage(frame, 1.0 / 255, (inWidth, inHeight), (0, 0, 0), swapRB=False, crop=False) net.setInput(inp) start_t = time.time() out = net.forward() kwinName = "Pose Estimation Demo: Cv-Tricks.com" cv.namedWindow(kwinName, cv.WINDOW_AUTOSIZE) try: points = [] for i in range(len(BODY_PARTS)): heatMap = out[0, i, :, :] _, conf, _, point = cv.minMaxLoc(heatMap) x = (frameWidth * point[0]) / out.shape[3] y = (frameHeight * point[1]) / out.shape[2] # Add a point if it's confidence is higher than threshold. points.append((int(x), int(y)) if conf > thr else None) y_aspect_ratio = points[8][1] - points[0][1] x_aspect_ratio = y_aspect_ratio top = [points[0][0], points[0][1]] bottom = [points[0][0], points[0][1] + y_aspect_ratio] left = [(points[0][0] - (x_aspect_ratio/2)), (points[0][1] + (y_aspect_ratio/2))] right = [(points[0][0] + (x_aspect_ratio/2)), (points[0][1] + (y_aspect_ratio/2))] frame = cv.cvtColor(frame, cv.COLOR_BGR2RGB) im = Image.fromarray(np.uint8(frame)) im = im.crop((left[0], top[1], right[0], bottom[1])) # im.save('output/{}'.format(input)) success += 1 # print('sucess') except Exception as e: print(e) falt += 1 # print("Success: {}".format(success)) # print("fault: {}".format(falt)) for pair in POSE_PAIRS: partFrom = pair[0] partTo = pair[1] assert(partFrom in BODY_PARTS) assert(partTo in BODY_PARTS) idFrom = BODY_PARTS[partFrom] idTo = BODY_PARTS[partTo] if points[idFrom] and points[idTo]: cv.line(frame, points[idFrom], points[idTo], (255, 74, 0), 3) cv.ellipse(frame, points[idFrom], (4, 4), 0, 0, 360, (255, 255, 255), cv.FILLED) cv.ellipse(frame, points[idTo], (4, 4), 0, 0, 360, (255, 255, 255), cv.FILLED) cv.putText(frame, str(idFrom), points[idFrom], cv.FONT_HERSHEY_SIMPLEX, 0.75, (255, 255, 255),2,cv.LINE_AA) cv.putText(frame, str(idTo), points[idTo], cv.FONT_HERSHEY_SIMPLEX, 0.75, (255, 255, 255),2,cv.LINE_AA) t, _ = net.getPerfProfile() freq = cv.getTickFrequency() / 1000 cv.putText(frame, '%.2fms' % (t / freq), (10, 20), cv.FONT_HERSHEY_SIMPLEX, 0.75, (255, 255, 255), 2, cv.LINE_AA) cv.imshow(kwinName, frame) cv.imwrite('output/'+input,frame)
[ "cv2.line", "numpy.uint8", "cv2.putText", "cv2.getTickFrequency", "cv2.cvtColor", "cv2.imwrite", "cv2.dnn.blobFromImage", "time.time", "cv2.imread", "cv2.ellipse", "cv2.dnn.readNetFromCaffe", "cv2.minMaxLoc", "cv2.imshow", "os.listdir", "cv2.namedWindow" ]
[((883, 920), 'cv2.dnn.readNetFromCaffe', 'cv.dnn.readNetFromCaffe', (['proto', 'model'], {}), '(proto, model)\n', (906, 920), True, 'import cv2 as cv\n'), ((981, 1002), 'os.listdir', 'os.listdir', (['image_dir'], {}), '(image_dir)\n', (991, 1002), False, 'import os\n'), ((1017, 1051), 'cv2.imread', 'cv.imread', (["(image_dir + '/' + input)"], {}), "(image_dir + '/' + input)\n", (1026, 1051), True, 'import cv2 as cv\n'), ((1127, 1227), 'cv2.dnn.blobFromImage', 'cv.dnn.blobFromImage', (['frame', '(1.0 / 255)', '(inWidth, inHeight)', '(0, 0, 0)'], {'swapRB': '(False)', 'crop': '(False)'}), '(frame, 1.0 / 255, (inWidth, inHeight), (0, 0, 0),\n swapRB=False, crop=False)\n', (1147, 1227), True, 'import cv2 as cv\n'), ((1294, 1305), 'time.time', 'time.time', ([], {}), '()\n', (1303, 1305), False, 'import time\n'), ((1388, 1432), 'cv2.namedWindow', 'cv.namedWindow', (['kwinName', 'cv.WINDOW_AUTOSIZE'], {}), '(kwinName, cv.WINDOW_AUTOSIZE)\n', (1402, 1432), True, 'import cv2 as cv\n'), ((3491, 3608), 'cv2.putText', 'cv.putText', (['frame', "('%.2fms' % (t / freq))", '(10, 20)', 'cv.FONT_HERSHEY_SIMPLEX', '(0.75)', '(255, 255, 255)', '(2)', 'cv.LINE_AA'], {}), "(frame, '%.2fms' % (t / freq), (10, 20), cv.FONT_HERSHEY_SIMPLEX,\n 0.75, (255, 255, 255), 2, cv.LINE_AA)\n", (3501, 3608), True, 'import cv2 as cv\n'), ((3610, 3636), 'cv2.imshow', 'cv.imshow', (['kwinName', 'frame'], {}), '(kwinName, frame)\n', (3619, 3636), True, 'import cv2 as cv\n'), ((3641, 3677), 'cv2.imwrite', 'cv.imwrite', (["('output/' + input)", 'frame'], {}), "('output/' + input, frame)\n", (3651, 3677), True, 'import cv2 as cv\n'), ((2248, 2284), 'cv2.cvtColor', 'cv.cvtColor', (['frame', 'cv.COLOR_BGR2RGB'], {}), '(frame, cv.COLOR_BGR2RGB)\n', (2259, 2284), True, 'import cv2 as cv\n'), ((3458, 3479), 'cv2.getTickFrequency', 'cv.getTickFrequency', ([], {}), '()\n', (3477, 3479), True, 'import cv2 as cv\n'), ((1576, 1597), 'cv2.minMaxLoc', 'cv.minMaxLoc', (['heatMap'], {}), '(heatMap)\n', (1588, 1597), True, 'import cv2 as cv\n'), ((2314, 2329), 'numpy.uint8', 'np.uint8', (['frame'], {}), '(frame)\n', (2322, 2329), True, 'import numpy as np\n'), ((2932, 2993), 'cv2.line', 'cv.line', (['frame', 'points[idFrom]', 'points[idTo]', '(255, 74, 0)', '(3)'], {}), '(frame, points[idFrom], points[idTo], (255, 74, 0), 3)\n', (2939, 2993), True, 'import cv2 as cv\n'), ((3006, 3091), 'cv2.ellipse', 'cv.ellipse', (['frame', 'points[idFrom]', '(4, 4)', '(0)', '(0)', '(360)', '(255, 255, 255)', 'cv.FILLED'], {}), '(frame, points[idFrom], (4, 4), 0, 0, 360, (255, 255, 255), cv.FILLED\n )\n', (3016, 3091), True, 'import cv2 as cv\n'), ((3099, 3177), 'cv2.ellipse', 'cv.ellipse', (['frame', 'points[idTo]', '(4, 4)', '(0)', '(0)', '(360)', '(255, 255, 255)', 'cv.FILLED'], {}), '(frame, points[idTo], (4, 4), 0, 0, 360, (255, 255, 255), cv.FILLED)\n', (3109, 3177), True, 'import cv2 as cv\n')]
import torch import torch.nn as nn import math import json import copy import numpy as np from deepxml.cornet import CorNet #%% def gelu(x): """Implementation of the gelu activation function. For information: OpenAI GPT's gelu is slightly different (and gives slightly different results): 0.5 * x * (1 + torch.tanh(math.sqrt(2 / math.pi) * (x + 0.044715 * torch.pow(x, 3)))) """ return x * 0.5 * (1.0 + torch.erf(x / math.sqrt(2.0))) def swish(x): return x * torch.sigmoid(x) ACT2FN = {"gelu": gelu, "relu": torch.nn.functional.relu, "swish": swish} #%% class BertConfig(object): """Configuration class to store the configuration of a `BertModel`. """ def __init__(self, vocab_size_or_config_json_file, hidden_size=768, num_hidden_layers=12, num_attention_heads=12, intermediate_size=3072, hidden_act="gelu", hidden_dropout_prob=0.1, attention_probs_dropout_prob=0.1, max_position_embeddings=512): """Constructs BertConfig. Args: vocab_size_or_config_json_file: Vocabulary size of `inputs_ids` in `BertModel`. hidden_size: Size of the encoder layers and the pooler layer. num_hidden_layers: Number of hidden layers in the Transformer encoder. num_attention_heads: Number of attention heads for each attention layer in the Transformer encoder. intermediate_size: The size of the "intermediate" (i.e., feed-forward) layer in the Transformer encoder. hidden_act: The non-linear activation function (function or string) in the encoder and pooler. If string, "gelu", "relu" and "swish" are supported. hidden_dropout_prob: The dropout probabilitiy for all fully connected layers in the embeddings, encoder, and pooler. attention_probs_dropout_prob: The dropout ratio for the attention probabilities. max_position_embeddings: The maximum sequence length that this model might ever be used with. Typically set this to something large just in case (e.g., 512 or 1024 or 2048). type_vocab_size: The vocabulary size of the `token_type_ids` passed into `BertModel`. initializer_range: The sttdev of the truncated_normal_initializer for initializing all weight matrices. """ if isinstance(vocab_size_or_config_json_file, str): with open(vocab_size_or_config_json_file, "r") as reader: json_config = json.loads(reader.read()) for key, value in json_config.items(): self.__dict__[key] = value elif isinstance(vocab_size_or_config_json_file, int): self.vocab_size = vocab_size_or_config_json_file self.hidden_size = hidden_size self.num_hidden_layers = num_hidden_layers self.num_attention_heads = num_attention_heads self.hidden_act = hidden_act self.intermediate_size = intermediate_size self.hidden_dropout_prob = hidden_dropout_prob self.attention_probs_dropout_prob = attention_probs_dropout_prob self.max_position_embeddings = max_position_embeddings else: raise ValueError("First argument must be either a vocabulary size (int)" "or the path to a pretrained model config file (str)") @classmethod def from_dict(cls, json_object): """Constructs a `BertConfig` from a Python dictionary of parameters.""" config = BertConfig(vocab_size_or_config_json_file=-1) for key, value in json_object.items(): config.__dict__[key] = value return config @classmethod def from_json_file(cls, json_file): """Constructs a `BertConfig` from a json file of parameters.""" with open(json_file, "r") as reader: text = reader.read() return cls.from_dict(json.loads(text)) def __repr__(self): return str(self.to_json_string()) def to_dict(self): """Serializes this instance to a Python dictionary.""" output = copy.deepcopy(self.__dict__) return output def to_json_string(self): """Serializes this instance to a JSON string.""" return json.dumps(self.to_dict(), indent=2, sort_keys=True) + "\n" #%% #class BertLayerNorm(nn.Module): # def __init__(self, config, variance_epsilon=1e-12): # """Construct a layernorm module in the TF style (epsilon inside the square root). # """ # super(BertLayerNorm, self).__init__() # self.gamma = nn.Parameter(torch.ones(config.hidden_size)) # self.beta = nn.Parameter(torch.zeros(config.hidden_size)) # self.variance_epsilon = variance_epsilon # # def forward(self, x): # u = x.mean(-1, keepdim=True) # s = (x - u).pow(2).mean(-1, keepdim=True) # x = (x - u) / torch.sqrt(s + self.variance_epsilon) # return self.gamma * x + self.beta class BertLayerNorm(nn.Module): def __init__(self, config): """Do nothing""" super(BertLayerNorm, self).__init__() def forward(self, x): return x #%% class BertEmbeddings(nn.Module): """Construct the embeddings from word, position and token_type embeddings. """ def __init__(self, config, emb_init, emb_trainable): super(BertEmbeddings, self).__init__() self.word_embeddings = nn.Embedding(config.vocab_size, config.hidden_size, _weight=torch.from_numpy(emb_init).float() if emb_init is not None else None) self.word_embeddings.weight.requires_grad = emb_trainable self.position_embeddings = nn.Embedding(config.max_position_embeddings, config.hidden_size) # self.token_type_embeddings = nn.Embedding(config.type_vocab_size, config.hidden_size) # self.LayerNorm is not snake-cased to stick with TensorFlow model variable name and be able to load # any TensorFlow checkpoint file self.LayerNorm = BertLayerNorm(config) self.dropout = nn.Dropout(config.hidden_dropout_prob) def forward(self, input_ids):#, token_type_ids=None): seq_length = input_ids.size(1) position_ids = torch.arange(seq_length, dtype=torch.long, device=input_ids.device) position_ids = position_ids.unsqueeze(0).expand_as(input_ids) # if token_type_ids is None: # token_type_ids = torch.zeros_like(input_ids) words_embeddings = self.word_embeddings(input_ids) position_embeddings = self.position_embeddings(position_ids) # token_type_embeddings = self.token_type_embeddings(token_type_ids) embeddings = words_embeddings + position_embeddings# + token_type_embeddings embeddings = self.LayerNorm(embeddings) embeddings = self.dropout(embeddings) return embeddings class BertSelfAttention(nn.Module): def __init__(self, config): super(BertSelfAttention, self).__init__() if config.hidden_size % config.num_attention_heads != 0: raise ValueError( "The hidden size (%d) is not a multiple of the number of attention " "heads (%d)" % (config.hidden_size, config.num_attention_heads)) self.num_attention_heads = config.num_attention_heads self.attention_head_size = int(config.hidden_size / config.num_attention_heads) self.all_head_size = self.num_attention_heads * self.attention_head_size self.query = nn.Linear(config.hidden_size, self.all_head_size) self.key = nn.Linear(config.hidden_size, self.all_head_size) self.value = nn.Linear(config.hidden_size, self.all_head_size) self.dropout = nn.Dropout(config.attention_probs_dropout_prob) def transpose_for_scores(self, x): new_x_shape = x.size()[:-1] + (self.num_attention_heads, self.attention_head_size) x = x.view(*new_x_shape) return x.permute(0, 2, 1, 3) def forward(self, hidden_states, attention_mask): mixed_query_layer = self.query(hidden_states) mixed_key_layer = self.key(hidden_states) mixed_value_layer = self.value(hidden_states) query_layer = self.transpose_for_scores(mixed_query_layer) key_layer = self.transpose_for_scores(mixed_key_layer) value_layer = self.transpose_for_scores(mixed_value_layer) # Take the dot product between "query" and "key" to get the raw attention scores. attention_scores = torch.matmul(query_layer, key_layer.transpose(-1, -2)) attention_scores = attention_scores / math.sqrt(self.attention_head_size) # Apply the attention mask is (precomputed for all layers in BertModel forward() function) attention_scores = attention_scores + attention_mask # Normalize the attention scores to probabilities. attention_probs = nn.Softmax(dim=-1)(attention_scores) # This is actually dropping out entire tokens to attend to, which might # seem a bit unusual, but is taken from the original Transformer paper. attention_probs = self.dropout(attention_probs) context_layer = torch.matmul(attention_probs, value_layer) context_layer = context_layer.permute(0, 2, 1, 3).contiguous() new_context_layer_shape = context_layer.size()[:-2] + (self.all_head_size,) context_layer = context_layer.view(*new_context_layer_shape) return context_layer class BertSelfOutput(nn.Module): def __init__(self, config): super(BertSelfOutput, self).__init__() self.dense = nn.Linear(config.hidden_size, config.hidden_size) self.LayerNorm = BertLayerNorm(config) self.dropout = nn.Dropout(config.hidden_dropout_prob) def forward(self, hidden_states, input_tensor): hidden_states = self.dense(hidden_states) hidden_states = self.dropout(hidden_states) hidden_states = self.LayerNorm(hidden_states + input_tensor) return hidden_states class BertAttention(nn.Module): def __init__(self, config): super(BertAttention, self).__init__() self.self = BertSelfAttention(config) self.output = BertSelfOutput(config) def forward(self, input_tensor, attention_mask): self_output = self.self(input_tensor, attention_mask) attention_output = self.output(self_output, input_tensor) return attention_output class BertIntermediate(nn.Module): def __init__(self, config): super(BertIntermediate, self).__init__() self.dense = nn.Linear(config.hidden_size, config.intermediate_size) self.intermediate_act_fn = ACT2FN[config.hidden_act] \ if isinstance(config.hidden_act, str) else config.hidden_act def forward(self, hidden_states): hidden_states = self.dense(hidden_states) hidden_states = self.intermediate_act_fn(hidden_states) return hidden_states class BertOutput(nn.Module): def __init__(self, config): super(BertOutput, self).__init__() self.dense = nn.Linear(config.intermediate_size, config.hidden_size) self.LayerNorm = BertLayerNorm(config) self.dropout = nn.Dropout(config.hidden_dropout_prob) def forward(self, hidden_states, input_tensor): hidden_states = self.dense(hidden_states) hidden_states = self.dropout(hidden_states) hidden_states = self.LayerNorm(hidden_states + input_tensor) return hidden_states class BertLayer(nn.Module): def __init__(self, config): super(BertLayer, self).__init__() self.attention = BertAttention(config) self.intermediate = BertIntermediate(config) self.output = BertOutput(config) def forward(self, hidden_states, attention_mask): attention_output = self.attention(hidden_states, attention_mask) intermediate_output = self.intermediate(attention_output) layer_output = self.output(intermediate_output, attention_output) return layer_output class BertEncoder(nn.Module): def __init__(self, config): super(BertEncoder, self).__init__() self.layer = nn.ModuleList([BertLayer(config) for _ in range(config.num_hidden_layers)]) def forward(self, hidden_states, attention_mask, output_all_encoded_layers=True): all_encoder_layers = [] for layer_module in self.layer: hidden_states = layer_module(hidden_states, attention_mask) if output_all_encoded_layers: all_encoder_layers.append(hidden_states) if not output_all_encoded_layers: all_encoder_layers.append(hidden_states) return all_encoder_layers #%% class BertLastSelfAttention(nn.Module): def __init__(self, config, n_probes): super(BertLastSelfAttention, self).__init__() self.n_probes = n_probes if config.hidden_size % config.num_attention_heads != 0: raise ValueError( "The hidden size (%d) is not a multiple of the number of attention " "heads (%d)" % (config.hidden_size, config.num_attention_heads)) self.num_attention_heads = config.num_attention_heads self.attention_head_size = int(config.hidden_size / config.num_attention_heads) self.all_head_size = self.num_attention_heads * self.attention_head_size self.query = nn.Linear(config.hidden_size, self.all_head_size) self.key = nn.Linear(config.hidden_size, self.all_head_size) self.value = nn.Linear(config.hidden_size, self.all_head_size) self.dropout = nn.Dropout(config.attention_probs_dropout_prob) def transpose_for_scores(self, x): new_x_shape = x.size()[:-1] + (self.num_attention_heads, self.attention_head_size) x = x.view(*new_x_shape) # batch, seq_len, n_heads, head_size return x.permute(0, 2, 1, 3) # batch, n_heads, seq_len, head_size def forward(self, hidden_states, attention_mask): mixed_query_layer = self.query(hidden_states[:, :self.n_probes, :]) mixed_key_layer = self.key(hidden_states) mixed_value_layer = self.value(hidden_states) query_layer = self.transpose_for_scores(mixed_query_layer) key_layer = self.transpose_for_scores(mixed_key_layer) value_layer = self.transpose_for_scores(mixed_value_layer) # Take the dot product between "query" and "key" to get the raw attention scores. attention_scores = torch.matmul(query_layer, key_layer.transpose(-1, -2)) # batch, n_heads, n_probes, seq_len attention_scores = attention_scores / math.sqrt(self.attention_head_size) # Apply the attention mask is (precomputed for all layers in BertModel forward() function) attention_scores = attention_scores + attention_mask # batch, n_heads, n_probes, seq_len # Normalize the attention scores to probabilities. attention_probs = nn.Softmax(dim=-1)(attention_scores) # This is actually dropping out entire tokens to attend to, which might # seem a bit unusual, but is taken from the original Transformer paper. attention_probs = self.dropout(attention_probs) # (batch, n_heads, n_probes, seq_len) * (batch, n_heads, seq_len, head_size) # -> (batch, n_heads, n_probes, head_size) context_layer = torch.matmul(attention_probs, value_layer) context_layer = context_layer.permute(0, 2, 1, 3).contiguous() # batch, n_probes, n_heads, head_size new_context_layer_shape = context_layer.size()[:-2] + (self.all_head_size,) context_layer = context_layer.view(*new_context_layer_shape) # batch, n_probes, hidden_size return context_layer class LastLayer(nn.Module): def __init__(self, config, n_probes): super(LastLayer, self).__init__() self.n_probes = n_probes self.selfattn = BertLastSelfAttention(config, n_probes) self.selfoutput = BertSelfOutput(config) self.intermediate = BertIntermediate(config) self.output = BertOutput(config) def forward(self, input_tensor, attention_mask): self_output = self.selfattn(input_tensor, attention_mask) attention_output = self.selfoutput(self_output, input_tensor[:, :self.n_probes, :]) intermediate_output = self.intermediate(attention_output) context_vectors = self.output(intermediate_output, attention_output) batch_size = context_vectors.size(0) context_vectors = context_vectors.view(batch_size, -1) return context_vectors #%% class BaseBertModel(nn.Module): def __init__(self, hidden_size, n_layers, n_probes, n_aheads, intermediate_size, dropout, hidden_act="relu", src_max_len=500, padding_idx=0, vocab_size=None, emb_init=None, emb_trainable=True, bottleneck_dim=None, **kwargs): super(BaseBertModel, self).__init__() self.initializer_range = 0.02 self.padding_idx = padding_idx if emb_init is not None: if vocab_size is not None: assert vocab_size == emb_init.shape[0] if hidden_size is not None: assert hidden_size == emb_init.shape[1] vocab_size, hidden_size = emb_init.shape self.register_buffer('tok_cls', torch.LongTensor([vocab_size + i for i in range(n_probes)])) vocab_size = vocab_size + n_probes emb_init = np.vstack((emb_init, np.random.normal(loc=0.0, scale=self.initializer_range, size=(n_probes, hidden_size)))) bertconfig = BertConfig(vocab_size, hidden_size, n_layers, n_aheads, intermediate_size, hidden_act=hidden_act, hidden_dropout_prob=dropout, attention_probs_dropout_prob=dropout, max_position_embeddings=src_max_len+n_probes) self.embeddings = BertEmbeddings(bertconfig, emb_init, emb_trainable) self.encoder = BertEncoder(bertconfig) self.lastlayer = LastLayer(bertconfig, n_probes) if bottleneck_dim is None: self.pooler = nn.Linear(hidden_size * n_probes, hidden_size * n_probes) else: self.pooler = nn.Linear(hidden_size * n_probes, bottleneck_dim) self.apply(self.init_bert_weights) def init_bert_weights(self, module): """ Initialize the weights. """ if isinstance(module, (nn.Linear, nn.Embedding)): # Slightly different from the TF version which uses truncated_normal for initialization # cf https://github.com/pytorch/pytorch/pull/5617 # module.weight.data.normal_(mean=0.0, std=self.initializer_range) nn.init.xavier_uniform_(module.weight) # alternative initialization elif isinstance(module, BertLayerNorm): pass # module.beta.data.normal_(mean=0.0, std=self.initializer_range) # module.gamma.data.normal_(mean=0.0, std=self.initializer_range) if isinstance(module, nn.Linear) and module.bias is not None: module.bias.data.zero_() def forward(self, raw_input_variables): cls_variables = self.tok_cls.expand(raw_input_variables.size(0), -1) input_variables = torch.cat((cls_variables, raw_input_variables), dim=1) attention_mask = input_variables != self.padding_idx extended_attention_mask = attention_mask.unsqueeze(1).unsqueeze(2) # batch, 1, 1, seq_len extended_attention_mask = extended_attention_mask.to(dtype=next(self.parameters()).dtype) # fp16 compatibility extended_attention_mask = (1.0 - extended_attention_mask) * -10000.0 embedding_output = self.embeddings(input_variables) encoded_layers = self.encoder(embedding_output, extended_attention_mask, output_all_encoded_layers=False) sequence_output = encoded_layers[-1] context_vectors = torch.nn.functional.elu(self.lastlayer(sequence_output, extended_attention_mask)) context_vectors = torch.nn.functional.elu(self.pooler(context_vectors)) return context_vectors # batch, n_probes * hidden_size class PlainC(nn.Module): def __init__(self, labels_num, hidden_size, n_probes): super(PlainC, self).__init__() self.out_mesh_dstrbtn = nn.Linear(hidden_size * n_probes, labels_num) nn.init.xavier_uniform_(self.out_mesh_dstrbtn.weight) def forward(self, context_vectors): output_dstrbtn = self.out_mesh_dstrbtn(context_vectors) return output_dstrbtn #%% class BertXML(nn.Module): def __init__(self, hidden_size, n_layers, n_aheads, intermediate_size, dropout, labels_num, n_probes, **kwargs): super(BertXML, self).__init__() self.tewp = BaseBertModel(hidden_size, n_layers, n_probes, n_aheads, intermediate_size, dropout, **kwargs) self.plaincls = PlainC(labels_num, hidden_size, n_probes) def forward(self, input_variables): context_vectors = self.tewp(input_variables) logits = self.plaincls(context_vectors) return logits class CorNetBertXML(nn.Module): def __init__(self, hidden_size, n_layers, n_aheads, intermediate_size, dropout, labels_num, n_probes, **kwargs): super(CorNetBertXML, self).__init__() self.bertxml = BertXML(hidden_size, n_layers, n_aheads, intermediate_size, dropout, labels_num, n_probes, **kwargs) self.cornet = CorNet(labels_num, **kwargs) def forward(self, input_variables): raw_logits = self.bertxml(input_variables) cor_logits = self.cornet(raw_logits) return cor_logits
[ "torch.nn.Dropout", "copy.deepcopy", "torch.from_numpy", "json.loads", "math.sqrt", "torch.nn.Embedding", "torch.nn.init.xavier_uniform_", "torch.cat", "torch.sigmoid", "torch.nn.Softmax", "torch.arange", "numpy.random.normal", "torch.nn.Linear", "torch.matmul", "deepxml.cornet.CorNet" ]
[((495, 511), 'torch.sigmoid', 'torch.sigmoid', (['x'], {}), '(x)\n', (508, 511), False, 'import torch\n'), ((4343, 4371), 'copy.deepcopy', 'copy.deepcopy', (['self.__dict__'], {}), '(self.__dict__)\n', (4356, 4371), False, 'import copy\n'), ((5930, 5994), 'torch.nn.Embedding', 'nn.Embedding', (['config.max_position_embeddings', 'config.hidden_size'], {}), '(config.max_position_embeddings, config.hidden_size)\n', (5942, 5994), True, 'import torch.nn as nn\n'), ((6311, 6349), 'torch.nn.Dropout', 'nn.Dropout', (['config.hidden_dropout_prob'], {}), '(config.hidden_dropout_prob)\n', (6321, 6349), True, 'import torch.nn as nn\n'), ((6471, 6538), 'torch.arange', 'torch.arange', (['seq_length'], {'dtype': 'torch.long', 'device': 'input_ids.device'}), '(seq_length, dtype=torch.long, device=input_ids.device)\n', (6483, 6538), False, 'import torch\n'), ((7748, 7797), 'torch.nn.Linear', 'nn.Linear', (['config.hidden_size', 'self.all_head_size'], {}), '(config.hidden_size, self.all_head_size)\n', (7757, 7797), True, 'import torch.nn as nn\n'), ((7817, 7866), 'torch.nn.Linear', 'nn.Linear', (['config.hidden_size', 'self.all_head_size'], {}), '(config.hidden_size, self.all_head_size)\n', (7826, 7866), True, 'import torch.nn as nn\n'), ((7888, 7937), 'torch.nn.Linear', 'nn.Linear', (['config.hidden_size', 'self.all_head_size'], {}), '(config.hidden_size, self.all_head_size)\n', (7897, 7937), True, 'import torch.nn as nn\n'), ((7962, 8009), 'torch.nn.Dropout', 'nn.Dropout', (['config.attention_probs_dropout_prob'], {}), '(config.attention_probs_dropout_prob)\n', (7972, 8009), True, 'import torch.nn as nn\n'), ((9402, 9444), 'torch.matmul', 'torch.matmul', (['attention_probs', 'value_layer'], {}), '(attention_probs, value_layer)\n', (9414, 9444), False, 'import torch\n'), ((9833, 9882), 'torch.nn.Linear', 'nn.Linear', (['config.hidden_size', 'config.hidden_size'], {}), '(config.hidden_size, config.hidden_size)\n', (9842, 9882), True, 'import torch.nn as nn\n'), ((9953, 9991), 'torch.nn.Dropout', 'nn.Dropout', (['config.hidden_dropout_prob'], {}), '(config.hidden_dropout_prob)\n', (9963, 9991), True, 'import torch.nn as nn\n'), ((10801, 10856), 'torch.nn.Linear', 'nn.Linear', (['config.hidden_size', 'config.intermediate_size'], {}), '(config.hidden_size, config.intermediate_size)\n', (10810, 10856), True, 'import torch.nn as nn\n'), ((11302, 11357), 'torch.nn.Linear', 'nn.Linear', (['config.intermediate_size', 'config.hidden_size'], {}), '(config.intermediate_size, config.hidden_size)\n', (11311, 11357), True, 'import torch.nn as nn\n'), ((11428, 11466), 'torch.nn.Dropout', 'nn.Dropout', (['config.hidden_dropout_prob'], {}), '(config.hidden_dropout_prob)\n', (11438, 11466), True, 'import torch.nn as nn\n'), ((13619, 13668), 'torch.nn.Linear', 'nn.Linear', (['config.hidden_size', 'self.all_head_size'], {}), '(config.hidden_size, self.all_head_size)\n', (13628, 13668), True, 'import torch.nn as nn\n'), ((13688, 13737), 'torch.nn.Linear', 'nn.Linear', (['config.hidden_size', 'self.all_head_size'], {}), '(config.hidden_size, self.all_head_size)\n', (13697, 13737), True, 'import torch.nn as nn\n'), ((13759, 13808), 'torch.nn.Linear', 'nn.Linear', (['config.hidden_size', 'self.all_head_size'], {}), '(config.hidden_size, self.all_head_size)\n', (13768, 13808), True, 'import torch.nn as nn\n'), ((13833, 13880), 'torch.nn.Dropout', 'nn.Dropout', (['config.attention_probs_dropout_prob'], {}), '(config.attention_probs_dropout_prob)\n', (13843, 13880), True, 'import torch.nn as nn\n'), ((15577, 15619), 'torch.matmul', 'torch.matmul', (['attention_probs', 'value_layer'], {}), '(attention_probs, value_layer)\n', (15589, 15619), False, 'import torch\n'), ((19465, 19519), 'torch.cat', 'torch.cat', (['(cls_variables, raw_input_variables)'], {'dim': '(1)'}), '((cls_variables, raw_input_variables), dim=1)\n', (19474, 19519), False, 'import torch\n'), ((20521, 20566), 'torch.nn.Linear', 'nn.Linear', (['(hidden_size * n_probes)', 'labels_num'], {}), '(hidden_size * n_probes, labels_num)\n', (20530, 20566), True, 'import torch.nn as nn\n'), ((20575, 20628), 'torch.nn.init.xavier_uniform_', 'nn.init.xavier_uniform_', (['self.out_mesh_dstrbtn.weight'], {}), '(self.out_mesh_dstrbtn.weight)\n', (20598, 20628), True, 'import torch.nn as nn\n'), ((21667, 21695), 'deepxml.cornet.CorNet', 'CorNet', (['labels_num'], {}), '(labels_num, **kwargs)\n', (21673, 21695), False, 'from deepxml.cornet import CorNet\n'), ((4154, 4170), 'json.loads', 'json.loads', (['text'], {}), '(text)\n', (4164, 4170), False, 'import json\n'), ((8841, 8876), 'math.sqrt', 'math.sqrt', (['self.attention_head_size'], {}), '(self.attention_head_size)\n', (8850, 8876), False, 'import math\n'), ((9123, 9141), 'torch.nn.Softmax', 'nn.Softmax', ([], {'dim': '(-1)'}), '(dim=-1)\n', (9133, 9141), True, 'import torch.nn as nn\n'), ((14844, 14879), 'math.sqrt', 'math.sqrt', (['self.attention_head_size'], {}), '(self.attention_head_size)\n', (14853, 14879), False, 'import math\n'), ((15162, 15180), 'torch.nn.Softmax', 'nn.Softmax', ([], {'dim': '(-1)'}), '(dim=-1)\n', (15172, 15180), True, 'import torch.nn as nn\n'), ((18313, 18370), 'torch.nn.Linear', 'nn.Linear', (['(hidden_size * n_probes)', '(hidden_size * n_probes)'], {}), '(hidden_size * n_probes, hidden_size * n_probes)\n', (18322, 18370), True, 'import torch.nn as nn\n'), ((18411, 18460), 'torch.nn.Linear', 'nn.Linear', (['(hidden_size * n_probes)', 'bottleneck_dim'], {}), '(hidden_size * n_probes, bottleneck_dim)\n', (18420, 18460), True, 'import torch.nn as nn\n'), ((18912, 18950), 'torch.nn.init.xavier_uniform_', 'nn.init.xavier_uniform_', (['module.weight'], {}), '(module.weight)\n', (18935, 18950), True, 'import torch.nn as nn\n'), ((17700, 17789), 'numpy.random.normal', 'np.random.normal', ([], {'loc': '(0.0)', 'scale': 'self.initializer_range', 'size': '(n_probes, hidden_size)'}), '(loc=0.0, scale=self.initializer_range, size=(n_probes,\n hidden_size))\n', (17716, 17789), True, 'import numpy as np\n'), ((448, 462), 'math.sqrt', 'math.sqrt', (['(2.0)'], {}), '(2.0)\n', (457, 462), False, 'import math\n'), ((5759, 5785), 'torch.from_numpy', 'torch.from_numpy', (['emb_init'], {}), '(emb_init)\n', (5775, 5785), False, 'import torch\n')]
# -*- coding: utf-8 -*- """ @author: <NAME> <<EMAIL>> <NAME> <<EMAIL>> """ import numpy as np NUM_FMT = '{:.4f}' def _table_format(data, headers=None, index=None, extra_spaces=0, h_bars=None): if headers is not None: data.insert(0, headers) if index is not None: index.insert(0, '') for idx, row in zip(index, data): row.insert(0, idx) column_widths = np.asarray([[len(str(v)) for v in row] for row in data]).max(axis=0) row_fmt = ' | '.join(['{:>%d}' % (w + extra_spaces) for w in column_widths][1:]) + '\n' if index is not None: row_fmt = '{:<%d} | ' % (column_widths[0] + extra_spaces) + row_fmt output = '' for i, row in enumerate(data): if h_bars is not None and i in h_bars: output += row_fmt.format(*['-' * (w + extra_spaces) for w in column_widths]).replace('|', '+') output += row_fmt.format(*row) return output class Result: """ Result Class for a single model """ def __init__(self, model_name, metric_avg_results, metric_user_results): self.model_name = model_name self.metric_avg_results = metric_avg_results self.metric_user_results = metric_user_results def __str__(self): headers = list(self.metric_avg_results.keys()) data = [[NUM_FMT.format(v) for v in self.metric_avg_results.values()]] return _table_format(data, headers, index=[self.model_name], h_bars=[1]) class CVResult(list): """ Cross Validation Result Class for a single model """ def __init__(self, model_name): super().__init__() self.model_name = model_name def __str__(self): return '[{}]\n{}'.format(self.model_name, self.table) def organize(self): headers = list(self[0].metric_avg_results.keys()) data, index = [], [] for f, r in enumerate(self): data.append([r.metric_avg_results[m] for m in headers]) index.append('Fold %d' % f) data = np.asarray(data) mean, std = data.mean(axis=0), data.std(axis=0) data = np.vstack([data, mean, std]) data = [[NUM_FMT.format(v) for v in row] for row in data] index.extend(['Mean', 'Std']) self.table = _table_format(data, headers, index, h_bars=[1, len(data) - 1]) class ExperimentResult(list): """ Result Class for an Experiment """ def __str__(self): headers = list(self[0].metric_avg_results.keys()) data, index = [], [] for r in self: data.append([NUM_FMT.format(r.metric_avg_results[m]) for m in headers]) index.append(r.model_name) return _table_format(data, headers, index, h_bars=[1]) class CVExperimentResult(ExperimentResult): """ Result Class for a cross-validation Experiment """ def __str__(self): return '\n'.join([r.__str__() for r in self])
[ "numpy.asarray", "numpy.vstack" ]
[((2025, 2041), 'numpy.asarray', 'np.asarray', (['data'], {}), '(data)\n', (2035, 2041), True, 'import numpy as np\n'), ((2113, 2141), 'numpy.vstack', 'np.vstack', (['[data, mean, std]'], {}), '([data, mean, std])\n', (2122, 2141), True, 'import numpy as np\n')]
import numpy as np import torch import logging from miso.metrics.continuous_metrics import ContinuousMetric from miso.losses.loss import MSECrossEntropyLoss, Loss from scipy.stats import pearsonr logger = logging.getLogger(__name__) np.set_printoptions(suppress=True) class NodeAttributeDecoder(torch.nn.Module): def __init__(self, input_dim, hidden_dim, output_dim, n_layers, loss_multiplier = 10, loss_function = Loss, activation = torch.nn.ReLU(), share_networks = False, dropout = 0.20, binary = False): super(NodeAttributeDecoder, self).__init__() self.input_dim = input_dim self.hidden_dim = hidden_dim self.output_dim = output_dim self.loss_multiplier = loss_multiplier self.binary = binary self.attr_loss_function = loss_function self.mask_loss_function = torch.nn.BCEWithLogitsLoss() self.dropout = torch.nn.Dropout(dropout) self.n_layers = n_layers self.activation = activation attr_input_layer = torch.nn.Linear(input_dim, hidden_dim) attr_hidden_layers = [torch.nn.Linear(hidden_dim, hidden_dim) for i in range(n_layers-1)] boolean_input_layer = torch.nn.Linear(input_dim, hidden_dim) boolean_hidden_layers = [torch.nn.Linear(hidden_dim, hidden_dim) for i in range(n_layers-1)] attr_output_layer = torch.nn.Linear(hidden_dim, output_dim) boolean_output_layer = torch.nn.Linear(hidden_dim, output_dim) all_attr_layers = [attr_input_layer] + attr_hidden_layers all_boolean_layers = [boolean_input_layer] + boolean_hidden_layers attr_net = [] boolean_net = [] for l in all_attr_layers: attr_net.append(l) attr_net.append(self.activation) attr_net.append(self.dropout) for l in all_boolean_layers: boolean_net.append(l) boolean_net.append(self.activation) boolean_net.append(self.dropout) attr_net.append(attr_output_layer) boolean_net.append(boolean_output_layer) self.attribute_network = torch.nn.Sequential(*attr_net) if share_networks: self.boolean_network = self.attribute_network else: self.boolean_network = torch.nn.Sequential(*boolean_net) self.metrics = ContinuousMetric(prefix = "node") def forward(self, decoder_output): """ decoder_output: batch, target_len, input_dim """ # get rid of eos output = decoder_output boolean_output = self.boolean_network(output) attr_output = self.attribute_network(output) #pred_mask = torch.gt(boolean_output, 0) #prod = attr_output[0] * pred_mask[0] #print(f"pred attr {prod[0:6, 0:8]}") return dict( pred_attributes= attr_output, pred_mask = boolean_output ) def compute_loss(self, predicted_attrs, predicted_mask, target_attrs, mask): # mask out non-predicted stuff to_mult = mask mask_binary = torch.gt(mask, 0).float() if self.binary: to_mult = mask_binary predicted_attrs = predicted_attrs * to_mult target_attrs = target_attrs * to_mult attr_loss = self.attr_loss_function(predicted_attrs, target_attrs) * self.loss_multiplier # see if annotated at all; don't model annotator confidence, already modeled above mask_loss = self.mask_loss_function(predicted_mask, mask_binary) * self.loss_multiplier predicted_attrs = predicted_attrs[mask_binary==1] target_attrs = target_attrs[mask_binary==1] flat_pred = predicted_attrs.reshape(-1).detach().cpu().numpy() flat_true = target_attrs.reshape(-1).detach().cpu().numpy() r, __ = pearsonr(flat_pred, flat_true) self.metrics(attr_loss.item()) self.metrics(mask_loss.item()) return dict(loss=attr_loss + mask_loss) @classmethod def from_params(cls, params, **kwargs): return cls(params['input_dim'], params['hidden_dim'], params['output_dim'], params['n_layers'], params.get("loss_multiplier", 10), params.get("loss_function", MSECrossEntropyLoss()), params.get("activation", torch.nn.ReLU()), params.get("share_networks", False))
[ "torch.nn.Dropout", "numpy.set_printoptions", "torch.nn.ReLU", "torch.nn.BCEWithLogitsLoss", "torch.nn.Sequential", "scipy.stats.pearsonr", "torch.gt", "torch.nn.Linear", "miso.metrics.continuous_metrics.ContinuousMetric", "miso.losses.loss.MSECrossEntropyLoss", "logging.getLogger" ]
[((208, 235), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (225, 235), False, 'import logging\n'), ((238, 272), 'numpy.set_printoptions', 'np.set_printoptions', ([], {'suppress': '(True)'}), '(suppress=True)\n', (257, 272), True, 'import numpy as np\n'), ((558, 573), 'torch.nn.ReLU', 'torch.nn.ReLU', ([], {}), '()\n', (571, 573), False, 'import torch\n'), ((1004, 1032), 'torch.nn.BCEWithLogitsLoss', 'torch.nn.BCEWithLogitsLoss', ([], {}), '()\n', (1030, 1032), False, 'import torch\n'), ((1057, 1082), 'torch.nn.Dropout', 'torch.nn.Dropout', (['dropout'], {}), '(dropout)\n', (1073, 1082), False, 'import torch\n'), ((1192, 1230), 'torch.nn.Linear', 'torch.nn.Linear', (['input_dim', 'hidden_dim'], {}), '(input_dim, hidden_dim)\n', (1207, 1230), False, 'import torch\n'), ((1389, 1427), 'torch.nn.Linear', 'torch.nn.Linear', (['input_dim', 'hidden_dim'], {}), '(input_dim, hidden_dim)\n', (1404, 1427), False, 'import torch\n'), ((1591, 1630), 'torch.nn.Linear', 'torch.nn.Linear', (['hidden_dim', 'output_dim'], {}), '(hidden_dim, output_dim)\n', (1606, 1630), False, 'import torch\n'), ((1662, 1701), 'torch.nn.Linear', 'torch.nn.Linear', (['hidden_dim', 'output_dim'], {}), '(hidden_dim, output_dim)\n', (1677, 1701), False, 'import torch\n'), ((2353, 2383), 'torch.nn.Sequential', 'torch.nn.Sequential', (['*attr_net'], {}), '(*attr_net)\n', (2372, 2383), False, 'import torch\n'), ((2577, 2608), 'miso.metrics.continuous_metrics.ContinuousMetric', 'ContinuousMetric', ([], {'prefix': '"""node"""'}), "(prefix='node')\n", (2593, 2608), False, 'from miso.metrics.continuous_metrics import ContinuousMetric\n'), ((4161, 4191), 'scipy.stats.pearsonr', 'pearsonr', (['flat_pred', 'flat_true'], {}), '(flat_pred, flat_true)\n', (4169, 4191), False, 'from scipy.stats import pearsonr\n'), ((1261, 1300), 'torch.nn.Linear', 'torch.nn.Linear', (['hidden_dim', 'hidden_dim'], {}), '(hidden_dim, hidden_dim)\n', (1276, 1300), False, 'import torch\n'), ((1461, 1500), 'torch.nn.Linear', 'torch.nn.Linear', (['hidden_dim', 'hidden_dim'], {}), '(hidden_dim, hidden_dim)\n', (1476, 1500), False, 'import torch\n'), ((2519, 2552), 'torch.nn.Sequential', 'torch.nn.Sequential', (['*boolean_net'], {}), '(*boolean_net)\n', (2538, 2552), False, 'import torch\n'), ((3423, 3440), 'torch.gt', 'torch.gt', (['mask', '(0)'], {}), '(mask, 0)\n', (3431, 3440), False, 'import torch\n'), ((4651, 4672), 'miso.losses.loss.MSECrossEntropyLoss', 'MSECrossEntropyLoss', ([], {}), '()\n', (4670, 4672), False, 'from miso.losses.loss import MSECrossEntropyLoss, Loss\n'), ((4720, 4735), 'torch.nn.ReLU', 'torch.nn.ReLU', ([], {}), '()\n', (4733, 4735), False, 'import torch\n')]
import pandas as pd import seaborn as sns import numpy as np import matplotlib.pyplot as plt import warnings warnings.filterwarnings('ignore') from sklearn import svm, tree, linear_model, neighbors, naive_bayes, ensemble, discriminant_analysis, gaussian_process from xgboost import XGBClassifier from sklearn.model_selection import StratifiedKFold, cross_val_score, GridSearchCV, train_test_split from sklearn.linear_model import LogisticRegressionCV from sklearn.feature_selection import RFECV import seaborn as sns from sklearn.preprocessing import OneHotEncoder, LabelEncoder, StandardScaler from sklearn import feature_selection from sklearn import metrics from sklearn.linear_model import LogisticRegression, RidgeClassifier from sklearn.ensemble import RandomForestClassifier from sklearn.discriminant_analysis import LinearDiscriminantAnalysis from sklearn.naive_bayes import GaussianNB from sklearn.model_selection import train_test_split def predict_round(pred_round): def load_afl_data(pred_round): df_2017 = pd.read_csv("../data/afl_results_2017.csv") #print(df_2017.shape) df_2018 = pd.read_csv("../data/afl_results_2018.csv") #print(df_2018.shape) df_2019 = pd.read_csv("../data/afl_results_2019.csv") #print(df_2019.shape) df_2020 = pd.read_csv("../data/afl_results_2020.csv") #print(df_2020.shape) df_2021 = pd.read_csv("../data/afl_results_2021.csv") #print(df_2021.shape) df_2022 = pd.read_csv("../data/afl_results_2022.csv") pred_round_results = df_2022[df_2022['round.roundNumber'] == pred_round] df_2022 = df_2022[df_2022['round.roundNumber'] < pred_round] #print(df_2022.shape) df_all = pd.concat([df_2017, df_2018, df_2019, df_2020, df_2021,df_2022], axis=0) df_all['Date'] = pd.to_datetime(df_all['match.date']).dt.strftime("%Y-%m-%d") df_players_2017 = pd.read_csv("../data/afl_players_stats_2017.csv") #print(df_players_2017.shape) df_players_2018 = pd.read_csv("../data/afl_players_stats_2018.csv") #print(df_players_2018.shape) df_players_2019 = pd.read_csv("../data/afl_players_stats_2019.csv") #print(df_players_2019.shape) df_players_2020 = pd.read_csv("../data/afl_players_stats_2020.csv") #print(df_players_2020.shape) df_players_2021 = pd.read_csv("../data/afl_players_stats_2021.csv") #print(df_players_2021.shape) df_players_2022 = pd.read_csv("../data/afl_players_stats_2022.csv") df_players_2022 = df_players_2022[df_players_2022['Round'] < pred_round] #print(df_players_2022.shape) df_players = pd.concat([df_players_2017, df_players_2018, df_players_2019,df_players_2020,df_players_2021,df_players_2022], axis=0) #print(df_players.shape) #df_players.columns df_fixture = pd.read_csv("../data/fixture_2022.csv") df_next_games_teams = df_fixture[(df_fixture['round.roundNumber'] == pred_round)] df_next_games_teams = df_next_games_teams[['home.team.name','away.team.name','venue.name','compSeason.year','round.roundNumber']] df_next_games_teams = df_next_games_teams.rename(columns={'home.team.name': 'match.homeTeam.name', 'away.team.name': 'match.awayTeam.name','compSeason.year':'round.year'}) df_next_games_teams['match.matchId'] = np.arange(len(df_next_games_teams)) return df_all, df_players, df_fixture, df_next_games_teams, pred_round_results def get_aggregate_player_stats(df=None): agg_stats = (df.rename(columns={ # Rename columns to lowercase 'Home.team': 'match.homeTeam.name', 'Away.team': 'match.awayTeam.name', }) .groupby(by=['Date', 'Season', 'match.homeTeam.name', 'match.awayTeam.name'], as_index=False) # Groupby to aggregate the stats for each game .sum() #.drop(columns=['DE', 'TOG', 'Match_id']) # Drop columns .assign(date=lambda df: pd.to_datetime(df.Date, format="%Y-%m-%d")) # Create a datetime object .sort_values(by='Date') .reset_index(drop=True)) return agg_stats df_all, df_players, df_fixture, df_next_games_teams, pred_round_results = load_afl_data(pred_round) agg_player = get_aggregate_player_stats(df_players) afl_df = df_all.merge(agg_player, on=['Date', 'match.homeTeam.name', 'match.awayTeam.name'], how='left') # Add average goal diff for home and away team rolling 4 games afl_df['HTGDIFF'] = afl_df['homeTeamScore.matchScore.goals'] - afl_df['awayTeamScore.matchScore.goals'] afl_df['ATGDIFF'] = afl_df['awayTeamScore.matchScore.goals'] - afl_df['homeTeamScore.matchScore.goals'] def from_dict_value_to_df(d): """ input = dictionary output = dataframe as part of all the values from the dictionary """ df = pd.DataFrame() for v in d.values(): df = pd.concat([df,v]) return df def avg_goal_diff(df, avg_h_a_diff, a_h_team, a_h_goal_letter): """ input: df = dataframe with all results avg_h_a_diff = name of the new column a_h_team = HomeTeam or AwayTeam a_h_goal_letter = 'H' for home or 'A' for away output: avg_per_team = dictionary with with team as key and columns as values with new column H/ATGDIFF """ df[avg_h_a_diff] = 0 avg_per_team = {} all_teams = df[a_h_team].unique() for t in all_teams: df_team = df[df[a_h_team]==t].fillna(0) result = df_team['{}TGDIFF'.format(a_h_goal_letter)].rolling(4).mean() df_team[avg_h_a_diff] = result avg_per_team[t] = df_team return avg_per_team d_AVGFTHG = avg_goal_diff(afl_df, 'AVGHTGDIFF', 'match.homeTeam.name', 'H') df_AVGFTHG = from_dict_value_to_df(d_AVGFTHG) df_AVGFTHG.sort_index(inplace=True) d_AVGFTAG = avg_goal_diff(df_AVGFTHG, 'AVGATGDIFF', 'match.awayTeam.name', 'A') afl_df = from_dict_value_to_df(d_AVGFTAG) afl_df.sort_index(inplace=True) afl_df['AVGATGDIFF'].fillna(0, inplace=True) afl_df['goal_diff'] = afl_df['homeTeamScore.matchScore.goals'] - afl_df['awayTeamScore.matchScore.goals'] for index, row in df_all[df_all['match.status']=='CONCLUDED'].iterrows(): if afl_df['goal_diff'][index] > 0: afl_df.at[index,'result'] = 1 # 1 is a win else: afl_df.at[index,'result'] = 0 # 0 is a loss def previous_data(df, h_or_a_team, column, letter, past_n): """ input: df = dataframe with all results a_h_team = HomeTeam or AwayTeam column = column selected to get previous data from output: team_with_past_dict = dictionary with team as a key and columns as values with new columns with past value """ d = dict() team_with_past_dict = dict() all_teams = df[h_or_a_team].unique() for team in all_teams: n_games = len(df[df[h_or_a_team]==team]) team_with_past_dict[team] = df[df[h_or_a_team]==team] for i in range(1, past_n): d[i] = team_with_past_dict[team].assign( result=team_with_past_dict[team].groupby(h_or_a_team)[column].shift(i) ).fillna({'{}_X'.format(column): 0}) team_with_past_dict[team]['{}_{}_{}'.format(letter, column, i)] = d[i].result return team_with_past_dict def previous_data_call(df, side, column, letter, iterations): d = previous_data(df, side, column, letter, iterations) df_result= from_dict_value_to_df(d) df_result.sort_index(inplace=True) return df_result df_last_home_results = previous_data_call(afl_df, 'match.homeTeam.name', 'result', 'H', 3) df_last_away_results = previous_data_call(df_last_home_results, 'match.awayTeam.name', 'result', 'A', 3) df_last_last_HTGDIFF_results = previous_data_call(df_last_away_results, 'match.homeTeam.name', 'HTGDIFF', 'H', 3) df_last_last_ATGDIFF_results = previous_data_call(df_last_last_HTGDIFF_results, 'match.awayTeam.name', 'ATGDIFF', 'A', 3) df_last_AVGFTHG_results = previous_data_call(df_last_last_ATGDIFF_results, 'match.homeTeam.name', 'AVGHTGDIFF', 'H', 2) df_last_AVGFTAG_results = previous_data_call(df_last_AVGFTHG_results, 'match.awayTeam.name', 'AVGATGDIFF', 'A', 2) afl_df = df_last_AVGFTAG_results.copy() all_cols = ['match.matchId','match.date', 'match.status', 'match.venue', 'match.homeTeam.name', 'match.awayTeam.name','venue.name', 'venue.state', 'round.name', 'round.year', 'round.roundNumber', 'status', 'homeTeamScore.rushedBehinds', 'homeTeamScore.minutesInFront', 'homeTeamScore.matchScore.totalScore', 'homeTeamScore.matchScore.goals', 'homeTeamScore.matchScore.behinds', 'homeTeamScore.matchScore.superGoals', 'awayTeamScore.rushedBehinds', 'awayTeamScore.minutesInFront', 'awayTeamScore.matchScore.totalScore', 'awayTeamScore.matchScore.goals', 'awayTeamScore.matchScore.behinds', 'awayTeamScore.matchScore.superGoals', 'weather.tempInCelsius', 'homeTeamScoreChart.goals', 'homeTeamScoreChart.leftBehinds', 'homeTeamScoreChart.rightBehinds', 'homeTeamScoreChart.leftPosters', 'homeTeamScoreChart.rightPosters', 'homeTeamScoreChart.rushedBehinds', 'homeTeamScoreChart.touchedBehinds', 'awayTeamScoreChart.goals', 'awayTeamScoreChart.leftBehinds', 'awayTeamScoreChart.rightBehinds', 'awayTeamScoreChart.leftPosters', 'awayTeamScoreChart.rightPosters', 'awayTeamScoreChart.rushedBehinds', 'awayTeamScoreChart.touchedBehinds', 'HQ1G', 'HQ1B', 'HQ2G', 'HQ2B', 'HQ3G', 'HQ3B', 'HQ4G', 'HQ4B', 'Home.score', 'AQ1G', 'AQ1B', 'AQ2G', 'AQ2B', 'AQ3G', 'AQ3B', 'AQ4G', 'AQ4B', 'Away.score', 'Kicks', 'Marks', 'Handballs', 'Goals', 'Behinds', 'Hit.Outs', 'Tackles', 'Rebounds', 'Inside.50s', 'Clearances', 'Clangers', 'Frees.For', 'Frees.Against', 'Brownlow.Votes', 'Contested.Possessions', 'Uncontested.Possessions', 'Contested.Marks', 'Marks.Inside.50', 'One.Percenters', 'Bounces', 'Goal.Assists', 'Time.on.Ground..', 'Substitute', 'group_id', 'HTGDIFF', 'ATGDIFF', 'AVGHTGDIFF', 'AVGATGDIFF', 'goal_diff', 'result', 'H_result_1', 'H_result_2', 'A_result_1', 'A_result_2', 'H_HTGDIFF_1', 'H_HTGDIFF_2', 'A_ATGDIFF_1', 'A_ATGDIFF_2', 'H_AVGHTGDIFF_1', 'A_AVGATGDIFF_1'] non_feature_cols = ['match.matchId','match.date', 'match.status', 'match.venue', 'match.homeTeam.name', 'match.awayTeam.name','venue.name', 'venue.state', 'round.name', 'round.year', 'round.roundNumber', 'status','Season'] feature_cols = [ 'homeTeamScore.rushedBehinds', 'homeTeamScore.minutesInFront', 'homeTeamScore.matchScore.totalScore', 'homeTeamScore.matchScore.goals', 'homeTeamScore.matchScore.behinds', 'homeTeamScore.matchScore.superGoals', 'awayTeamScore.rushedBehinds', 'awayTeamScore.minutesInFront', 'awayTeamScore.matchScore.totalScore', 'awayTeamScore.matchScore.goals', 'awayTeamScore.matchScore.behinds', 'awayTeamScore.matchScore.superGoals', 'weather.tempInCelsius', 'homeTeamScoreChart.goals', 'homeTeamScoreChart.leftBehinds', 'homeTeamScoreChart.rightBehinds', 'homeTeamScoreChart.leftPosters', 'homeTeamScoreChart.rightPosters', 'homeTeamScoreChart.rushedBehinds', 'homeTeamScoreChart.touchedBehinds', 'awayTeamScoreChart.goals', 'awayTeamScoreChart.leftBehinds', 'awayTeamScoreChart.rightBehinds', 'awayTeamScoreChart.leftPosters', 'awayTeamScoreChart.rightPosters', 'awayTeamScoreChart.rushedBehinds', 'awayTeamScoreChart.touchedBehinds', 'HQ1G', 'HQ1B', 'HQ2G', 'HQ2B', 'HQ3G', 'HQ3B', 'HQ4G', 'HQ4B', 'Home.score', 'AQ1G', 'AQ1B', 'AQ2G', 'AQ2B', 'AQ3G', 'AQ3B', 'AQ4G', 'AQ4B', 'Away.score', 'Kicks', 'Marks', 'Handballs', 'Goals', 'Behinds', 'Hit.Outs', 'Tackles', 'Rebounds', 'Inside.50s', 'Clearances', 'Clangers', 'Frees.For', 'Frees.Against', 'Brownlow.Votes', 'Contested.Possessions', 'Uncontested.Possessions', 'Contested.Marks', 'Marks.Inside.50', 'One.Percenters', 'Bounces', 'Goal.Assists', 'Time.on.Ground..', 'Substitute', 'group_id', 'HTGDIFF', 'ATGDIFF', 'AVGHTGDIFF', 'AVGATGDIFF', 'goal_diff', 'result', 'H_result_1', 'H_result_2', 'A_result_1', 'A_result_2', 'H_HTGDIFF_1', 'H_HTGDIFF_2', 'A_ATGDIFF_1', 'A_ATGDIFF_2', 'H_AVGHTGDIFF_1', 'A_AVGATGDIFF_1'] afl_df = afl_df[all_cols] afl_df = afl_df.rename(columns={col: 'f_' + col for col in afl_df if col not in non_feature_cols}) def create_training_and_test_data(afl_df,df_next_games_teams): # Define a function which returns a DataFrame with the expontential moving average for each numeric stat def create_exp_weighted_avgs(df, span): # Create a copy of the df with only the game id and the team - we will add cols to this df ema_features = df[['match.matchId', 'match.homeTeam.name']].copy() feature_names = [col for col in df.columns if col.startswith('f_')] # Get a list of columns we will iterate over for feature_name in feature_names: feature_ema = (df.groupby('match.homeTeam.name')[feature_name] .transform(lambda row: (row.ewm(span=span) .mean() .shift(1)))) ema_features[feature_name] = feature_ema return ema_features # Define a function which finds the elo for each team in each game and returns a dictionary with the game ID as a key and the # elos as the key's value, in a list. It also outputs the probabilities and a dictionary of the final elos for each team def elo_applier(df, k_factor): # Initialise a dictionary with default elos for each team elo_dict = {team: 1500 for team in df['match.homeTeam.name'].unique()} elos, elo_probs = {}, {} # Get a home and away dataframe so that we can get the teams on the same row #home_df = df.loc[df.home_game == 1, ['match.homeTeam.name', 'match.matchId', 'f_margin', 'home_game']].rename(columns={'team': 'home_team'}) #away_df = df.loc[df.home_game == 0, ['match.homeTeam.name', 'match.matchId']].rename(columns={'team': 'away_team'}) #df = (pd.merge(home_df, away_df, on='game') # .sort_values(by='game') # .drop_duplicates(subset='game', keep='first') # .reset_index(drop=True)) # Loop over the rows in the DataFrame for index, row in df.iterrows(): # Get the Game ID game_id = row['match.matchId'] # Get the margin margin = row['f_goal_diff'] # If the game already has the elos for the home and away team in the elos dictionary, go to the next game if game_id in elos.keys(): continue # Get the team and opposition home_team = row['match.homeTeam.name'] away_team = row['match.awayTeam.name'] # Get the team and opposition elo score home_team_elo = elo_dict[home_team] away_team_elo = elo_dict[away_team] # Calculated the probability of winning for the team and opposition prob_win_home = 1 / (1 + 10**((away_team_elo - home_team_elo) / 400)) prob_win_away = 1 - prob_win_home # Add the elos and probabilities our elos dictionary and elo_probs dictionary based on the Game ID elos[game_id] = [home_team_elo, away_team_elo] elo_probs[game_id] = [prob_win_home, prob_win_away] # Calculate the new elos of each team if margin > 0: # Home team wins; update both teams' elo new_home_team_elo = home_team_elo + k_factor*(1 - prob_win_home) new_away_team_elo = away_team_elo + k_factor*(0 - prob_win_away) elif margin < 0: # Away team wins; update both teams' elo new_home_team_elo = home_team_elo + k_factor*(0 - prob_win_home) new_away_team_elo = away_team_elo + k_factor*(1 - prob_win_away) elif margin == 0: # Drawn game' update both teams' elo new_home_team_elo = home_team_elo + k_factor*(0.5 - prob_win_home) new_away_team_elo = away_team_elo + k_factor*(0.5 - prob_win_away) # Update elos in elo dictionary elo_dict[home_team] = new_home_team_elo elo_dict[away_team] = new_away_team_elo return elos, elo_probs, elo_dict afl_df['train_data'] = 1 df_next_games_teams['train_data'] = 0 afl_data = afl_df.append(df_next_games_teams).reset_index(drop=True) features_rolling_averages = create_exp_weighted_avgs(afl_data, span=10) features = afl_data[['match.date', 'match.matchId', 'match.homeTeam.name', 'match.awayTeam.name', 'venue.name','round.year','train_data']].copy() features = pd.merge(features, features_rolling_averages, on=['match.matchId', 'match.homeTeam.name']) form_btwn_teams = afl_df[['match.matchId', 'match.homeTeam.name', 'match.awayTeam.name', 'f_goal_diff']].copy() elos, elo_probs, elo_dict = elo_applier(afl_data, 30) # Add our created features - elo, efficiency etc. #features = (features.assign(f_elo_home=lambda df: df['match.matchId'].map(elos).apply(lambda x: x[0]), # f_elo_away=lambda df: df['match.matchId'].map(elos).apply(lambda x: x[1])) # .reset_index(drop=True)) # form_btwn_teams_inv = pd.DataFrame() # for index, row in form_btwn_teams.iterrows(): # home = row['match.homeTeam.name'] # away = row['match.awayTeam.name'] # matchid = row['match.matchId'] # margin = row['f_goal_diff'] # form_btwn_teams_inv = form_btwn_teams_inv.append({'match.matchId': matchid, 'match.homeTeam.name': away, 'match.awayTeam.name': home, 'f_goal_diff': -1*margin}, ignore_index=True) # form_btwn_teams['f_form_margin_btwn_teams'] = (form_btwn_teams.groupby(['match.homeTeam.name', 'match.awayTeam.name'])['f_goal_diff'] # .transform(lambda row: row.rolling(5).mean().shift()) # .fillna(0)) # form_btwn_teams['f_form_past_5_btwn_teams'] = \ # (form_btwn_teams.assign(win=lambda df: df.apply(lambda row: 1 if row.f_goal_diff > 0 else 0, axis='columns')) # .groupby(['match.homeTeam.name', 'match.awayTeam.name'])['win'] # .transform(lambda row: row.rolling(5).mean().shift() * 5) # .fillna(0)) #print(features.shape) # Merge to our features df #features = pd.merge(features, form_btwn_teams_1.drop(columns=['f_goal_diff']), on=['match.matchId', 'match.homeTeam.name', 'match.awayTeam.name']) #print(features.shape) # Get the result and merge to the feature_df match_results = (afl_df.assign(result=lambda df: df.apply(lambda row: 1 if row['f_goal_diff'] > 0 else 0, axis=1))) # Merge result column to feature_df feature_df = pd.merge(features, match_results[['match.matchId', 'result']], on='match.matchId') return feature_df,features_rolling_averages, afl_data, features feature_df, features_rolling_averages, afl_data, features = create_training_and_test_data(afl_df,df_next_games_teams) feature_columns = [col for col in feature_df if col.startswith('f_')] #features['f_elo_home'] = features['f_elo_home']/1500 #features['f_elo_away'] = features['f_elo_away']/1500 # Build model from feature_df feature_df = feature_df.dropna() all_X = feature_df.loc[:, feature_columns] all_y = feature_df.loc[:, 'result'] X_train, X_test, y_train, y_test = train_test_split(all_X, all_y, test_size=0.30, random_state=42) # Scale features scaler = StandardScaler() X_train[feature_columns] = scaler.fit_transform(X_train[feature_columns]) X_test[feature_columns] = scaler.transform(X_test[feature_columns]) # Create a list of standard classifiers classifiers = [ #Ensemble Methods ensemble.AdaBoostClassifier(), ensemble.BaggingClassifier(), ensemble.ExtraTreesClassifier(), ensemble.GradientBoostingClassifier(), ensemble.RandomForestClassifier(), #Gaussian Processes gaussian_process.GaussianProcessClassifier(), #GLM linear_model.LogisticRegressionCV(), #Navies Bayes naive_bayes.BernoulliNB(), naive_bayes.GaussianNB(), #SVM svm.SVC(probability=True), svm.NuSVC(probability=True), #Discriminant Analysis discriminant_analysis.LinearDiscriminantAnalysis(), discriminant_analysis.QuadraticDiscriminantAnalysis(), #xgboost: http://xgboost.readthedocs.io/en/latest/model.html #XGBClassifier() ] # Define a functiom which finds the best algorithms for our modelling task def find_best_algorithms(classifier_list, X, y): # This function is adapted from https://www.kaggle.com/yassineghouzam/titanic-top-4-with-ensemble-modeling # Cross validate model with Kfold stratified cross validation kfold = StratifiedKFold(n_splits=5) # Grab the cross validation scores for each algorithm cv_results = [cross_val_score(classifier, X, y, scoring = "neg_log_loss", cv = kfold) for classifier in classifier_list] cv_means = [cv_result.mean() * -1 for cv_result in cv_results] cv_std = [cv_result.std() for cv_result in cv_results] algorithm_names = [alg.__class__.__name__ for alg in classifiers] # Create a DataFrame of all the CV results cv_results = pd.DataFrame({ "Mean Log Loss": cv_means, "Log Loss Std": cv_std, "Algorithm": algorithm_names }) return cv_results.sort_values(by='Mean Log Loss').reset_index(drop=True) best_algos = find_best_algorithms(classifiers, X_train, y_train) # Define a function which optimises the hyperparameters of our chosen algorithms def optimise_hyperparameters(train_x, train_y, algorithms, parameters): kfold = StratifiedKFold(n_splits=5) best_estimators = [] for alg, params in zip(algorithms, parameters): gs = GridSearchCV(alg, param_grid=params, cv=kfold, scoring='neg_log_loss', verbose=1) gs.fit(train_x, train_y) best_estimators.append(gs.best_estimator_) return best_estimators # Define our parameters to run a grid search over lr_grid = { "C": [0.0001, 0.001, 0.01, 0.05, 0.2, 0.5], "solver": ["newton-cg", "lbfgs", "liblinear"] } # Add our algorithms and parameters to lists to be used in our function alg_list = [LogisticRegression(), ensemble.RandomForestClassifier()] param_list = [lr_grid] # Find the best estimators, then add our other estimators which don't need optimisation best_estimators = optimise_hyperparameters(X_train, y_train, alg_list, param_list) lr_best_params = best_estimators[0].get_params() lr = LogisticRegression(**lr_best_params) lr.fit(X_train, y_train) final_predictions_lr = lr.predict(X_test) accuracy = (final_predictions_lr == y_test).mean() * 100 next_round_features = features[features['train_data']==0][feature_columns] next_round_predictions = lr.predict(next_round_features) prediction_probs = lr.predict_proba(next_round_features) df_next_games_teams['pred_home_result'] = next_round_predictions df_next_games_teams['pred_home_prob'] = prediction_probs[:,1].round(3) if len(pred_round_results)==0: return accuracy, df_next_games_teams, features, afl_df pred_round_results['result'] = np.where(pred_round_results['homeTeamScore.matchScore.totalScore']>pred_round_results['awayTeamScore.matchScore.totalScore'],1,0) actual_results = pred_round_results[['match.homeTeam.name','match.awayTeam.name','round.roundNumber','homeTeamScore.matchScore.totalScore','awayTeamScore.matchScore.totalScore','result']] df_next_games_teams = pd.merge(df_next_games_teams, actual_results, on=['match.homeTeam.name', 'match.awayTeam.name']) df_next_games_teams['score_1'] = 0.0 df_next_games_teams['score_2'] = 0.0 df_next_games_teams['score_3'] = 0.0 for i in range(len(df_next_games_teams)): p = df_next_games_teams['pred_home_prob'].values[i] orig_p = df_next_games_teams['pred_home_prob'].values[i] if p > 0.9: p = 0.9 elif p < 0.1: p = 0.1 if df_next_games_teams['homeTeamScore.matchScore.totalScore'].values[i] == df_next_games_teams['awayTeamScore.matchScore.totalScore'].values[i]: df_next_games_teams['score_1'].values[i] = 1.0 + 0.5 * np.log2(p*(1-p)) df_next_games_teams['score_2'].values[i] = 1.0 + 0.5 * np.log2(p*(1-p)) df_next_games_teams['score_3'].values[i] = 1.0 + 0.5 * np.log2(orig_p*(1-orig_p)) elif (df_next_games_teams['pred_home_result'].values[i] == df_next_games_teams['result'].values[i]): df_next_games_teams['score_1'].values[i] = 1.0 + np.log2(p) if df_next_games_teams['pred_home_result'].values[i] == 1: df_next_games_teams['score_1'].values[i] = 1.0 + np.log2(p) df_next_games_teams['score_3'].values[i] = 1.0 + np.log2(orig_p) else: df_next_games_teams['score_2'].values[i] = 1.0 + np.log2(1-p) df_next_games_teams['score_3'].values[i] = 1.0 + np.log2(1-orig_p) elif df_next_games_teams['pred_home_result'].values[i] != df_next_games_teams['result'].values[i]: df_next_games_teams['score_1'].values[i] = 1.0 + np.log2(1.0 - p) df_next_games_teams['score_2'].values[i] = 1.0 + np.log2(1.0 - p) df_next_games_teams['score_3'].values[i] = 1.0 + np.log2(1.0 - orig_p) return accuracy, df_next_games_teams, features, afl_df
[ "sklearn.model_selection.GridSearchCV", "sklearn.preprocessing.StandardScaler", "pandas.read_csv", "sklearn.model_selection.train_test_split", "sklearn.model_selection.cross_val_score", "sklearn.svm.SVC", "sklearn.discriminant_analysis.QuadraticDiscriminantAnalysis", "pandas.DataFrame", "pandas.merg...
[((110, 143), 'warnings.filterwarnings', 'warnings.filterwarnings', (['"""ignore"""'], {}), "('ignore')\n", (133, 143), False, 'import warnings\n'), ((20988, 21050), 'sklearn.model_selection.train_test_split', 'train_test_split', (['all_X', 'all_y'], {'test_size': '(0.3)', 'random_state': '(42)'}), '(all_X, all_y, test_size=0.3, random_state=42)\n', (21004, 21050), False, 'from sklearn.model_selection import train_test_split\n'), ((21087, 21103), 'sklearn.preprocessing.StandardScaler', 'StandardScaler', ([], {}), '()\n', (21101, 21103), False, 'from sklearn.preprocessing import OneHotEncoder, LabelEncoder, StandardScaler\n'), ((24462, 24498), 'sklearn.linear_model.LogisticRegression', 'LogisticRegression', ([], {}), '(**lr_best_params)\n', (24480, 24498), False, 'from sklearn.linear_model import LogisticRegression, RidgeClassifier\n'), ((25142, 25279), 'numpy.where', 'np.where', (["(pred_round_results['homeTeamScore.matchScore.totalScore'] >\n pred_round_results['awayTeamScore.matchScore.totalScore'])", '(1)', '(0)'], {}), "(pred_round_results['homeTeamScore.matchScore.totalScore'] >\n pred_round_results['awayTeamScore.matchScore.totalScore'], 1, 0)\n", (25150, 25279), True, 'import numpy as np\n'), ((25500, 25600), 'pandas.merge', 'pd.merge', (['df_next_games_teams', 'actual_results'], {'on': "['match.homeTeam.name', 'match.awayTeam.name']"}), "(df_next_games_teams, actual_results, on=['match.homeTeam.name',\n 'match.awayTeam.name'])\n", (25508, 25600), True, 'import pandas as pd\n'), ((1034, 1077), 'pandas.read_csv', 'pd.read_csv', (['"""../data/afl_results_2017.csv"""'], {}), "('../data/afl_results_2017.csv')\n", (1045, 1077), True, 'import pandas as pd\n'), ((1126, 1169), 'pandas.read_csv', 'pd.read_csv', (['"""../data/afl_results_2018.csv"""'], {}), "('../data/afl_results_2018.csv')\n", (1137, 1169), True, 'import pandas as pd\n'), ((1218, 1261), 'pandas.read_csv', 'pd.read_csv', (['"""../data/afl_results_2019.csv"""'], {}), "('../data/afl_results_2019.csv')\n", (1229, 1261), True, 'import pandas as pd\n'), ((1310, 1353), 'pandas.read_csv', 'pd.read_csv', (['"""../data/afl_results_2020.csv"""'], {}), "('../data/afl_results_2020.csv')\n", (1321, 1353), True, 'import pandas as pd\n'), ((1402, 1445), 'pandas.read_csv', 'pd.read_csv', (['"""../data/afl_results_2021.csv"""'], {}), "('../data/afl_results_2021.csv')\n", (1413, 1445), True, 'import pandas as pd\n'), ((1494, 1537), 'pandas.read_csv', 'pd.read_csv', (['"""../data/afl_results_2022.csv"""'], {}), "('../data/afl_results_2022.csv')\n", (1505, 1537), True, 'import pandas as pd\n'), ((1744, 1817), 'pandas.concat', 'pd.concat', (['[df_2017, df_2018, df_2019, df_2020, df_2021, df_2022]'], {'axis': '(0)'}), '([df_2017, df_2018, df_2019, df_2020, df_2021, df_2022], axis=0)\n', (1753, 1817), True, 'import pandas as pd\n'), ((1929, 1978), 'pandas.read_csv', 'pd.read_csv', (['"""../data/afl_players_stats_2017.csv"""'], {}), "('../data/afl_players_stats_2017.csv')\n", (1940, 1978), True, 'import pandas as pd\n'), ((2043, 2092), 'pandas.read_csv', 'pd.read_csv', (['"""../data/afl_players_stats_2018.csv"""'], {}), "('../data/afl_players_stats_2018.csv')\n", (2054, 2092), True, 'import pandas as pd\n'), ((2157, 2206), 'pandas.read_csv', 'pd.read_csv', (['"""../data/afl_players_stats_2019.csv"""'], {}), "('../data/afl_players_stats_2019.csv')\n", (2168, 2206), True, 'import pandas as pd\n'), ((2271, 2320), 'pandas.read_csv', 'pd.read_csv', (['"""../data/afl_players_stats_2020.csv"""'], {}), "('../data/afl_players_stats_2020.csv')\n", (2282, 2320), True, 'import pandas as pd\n'), ((2385, 2434), 'pandas.read_csv', 'pd.read_csv', (['"""../data/afl_players_stats_2021.csv"""'], {}), "('../data/afl_players_stats_2021.csv')\n", (2396, 2434), True, 'import pandas as pd\n'), ((2499, 2548), 'pandas.read_csv', 'pd.read_csv', (['"""../data/afl_players_stats_2022.csv"""'], {}), "('../data/afl_players_stats_2022.csv')\n", (2510, 2548), True, 'import pandas as pd\n'), ((2698, 2823), 'pandas.concat', 'pd.concat', (['[df_players_2017, df_players_2018, df_players_2019, df_players_2020,\n df_players_2021, df_players_2022]'], {'axis': '(0)'}), '([df_players_2017, df_players_2018, df_players_2019,\n df_players_2020, df_players_2021, df_players_2022], axis=0)\n', (2707, 2823), True, 'import pandas as pd\n'), ((2908, 2947), 'pandas.read_csv', 'pd.read_csv', (['"""../data/fixture_2022.csv"""'], {}), "('../data/fixture_2022.csv')\n", (2919, 2947), True, 'import pandas as pd\n'), ((5042, 5056), 'pandas.DataFrame', 'pd.DataFrame', ([], {}), '()\n', (5054, 5056), True, 'import pandas as pd\n'), ((17940, 18034), 'pandas.merge', 'pd.merge', (['features', 'features_rolling_averages'], {'on': "['match.matchId', 'match.homeTeam.name']"}), "(features, features_rolling_averages, on=['match.matchId',\n 'match.homeTeam.name'])\n", (17948, 18034), True, 'import pandas as pd\n'), ((20318, 20405), 'pandas.merge', 'pd.merge', (['features', "match_results[['match.matchId', 'result']]"], {'on': '"""match.matchId"""'}), "(features, match_results[['match.matchId', 'result']], on=\n 'match.matchId')\n", (20326, 20405), True, 'import pandas as pd\n'), ((21353, 21382), 'sklearn.ensemble.AdaBoostClassifier', 'ensemble.AdaBoostClassifier', ([], {}), '()\n', (21380, 21382), False, 'from sklearn import svm, tree, linear_model, neighbors, naive_bayes, ensemble, discriminant_analysis, gaussian_process\n'), ((21392, 21420), 'sklearn.ensemble.BaggingClassifier', 'ensemble.BaggingClassifier', ([], {}), '()\n', (21418, 21420), False, 'from sklearn import svm, tree, linear_model, neighbors, naive_bayes, ensemble, discriminant_analysis, gaussian_process\n'), ((21430, 21461), 'sklearn.ensemble.ExtraTreesClassifier', 'ensemble.ExtraTreesClassifier', ([], {}), '()\n', (21459, 21461), False, 'from sklearn import svm, tree, linear_model, neighbors, naive_bayes, ensemble, discriminant_analysis, gaussian_process\n'), ((21471, 21508), 'sklearn.ensemble.GradientBoostingClassifier', 'ensemble.GradientBoostingClassifier', ([], {}), '()\n', (21506, 21508), False, 'from sklearn import svm, tree, linear_model, neighbors, naive_bayes, ensemble, discriminant_analysis, gaussian_process\n'), ((21518, 21551), 'sklearn.ensemble.RandomForestClassifier', 'ensemble.RandomForestClassifier', ([], {}), '()\n', (21549, 21551), False, 'from sklearn import svm, tree, linear_model, neighbors, naive_bayes, ensemble, discriminant_analysis, gaussian_process\n'), ((21590, 21634), 'sklearn.gaussian_process.GaussianProcessClassifier', 'gaussian_process.GaussianProcessClassifier', ([], {}), '()\n', (21632, 21634), False, 'from sklearn import svm, tree, linear_model, neighbors, naive_bayes, ensemble, discriminant_analysis, gaussian_process\n'), ((21666, 21701), 'sklearn.linear_model.LogisticRegressionCV', 'linear_model.LogisticRegressionCV', ([], {}), '()\n', (21699, 21701), False, 'from sklearn import svm, tree, linear_model, neighbors, naive_bayes, ensemble, discriminant_analysis, gaussian_process\n'), ((21742, 21767), 'sklearn.naive_bayes.BernoulliNB', 'naive_bayes.BernoulliNB', ([], {}), '()\n', (21765, 21767), False, 'from sklearn import svm, tree, linear_model, neighbors, naive_bayes, ensemble, discriminant_analysis, gaussian_process\n'), ((21777, 21801), 'sklearn.naive_bayes.GaussianNB', 'naive_bayes.GaussianNB', ([], {}), '()\n', (21799, 21801), False, 'from sklearn import svm, tree, linear_model, neighbors, naive_bayes, ensemble, discriminant_analysis, gaussian_process\n'), ((21833, 21858), 'sklearn.svm.SVC', 'svm.SVC', ([], {'probability': '(True)'}), '(probability=True)\n', (21840, 21858), False, 'from sklearn import svm, tree, linear_model, neighbors, naive_bayes, ensemble, discriminant_analysis, gaussian_process\n'), ((21868, 21895), 'sklearn.svm.NuSVC', 'svm.NuSVC', ([], {'probability': '(True)'}), '(probability=True)\n', (21877, 21895), False, 'from sklearn import svm, tree, linear_model, neighbors, naive_bayes, ensemble, discriminant_analysis, gaussian_process\n'), ((21945, 21995), 'sklearn.discriminant_analysis.LinearDiscriminantAnalysis', 'discriminant_analysis.LinearDiscriminantAnalysis', ([], {}), '()\n', (21993, 21995), False, 'from sklearn import svm, tree, linear_model, neighbors, naive_bayes, ensemble, discriminant_analysis, gaussian_process\n'), ((22005, 22058), 'sklearn.discriminant_analysis.QuadraticDiscriminantAnalysis', 'discriminant_analysis.QuadraticDiscriminantAnalysis', ([], {}), '()\n', (22056, 22058), False, 'from sklearn import svm, tree, linear_model, neighbors, naive_bayes, ensemble, discriminant_analysis, gaussian_process\n'), ((22508, 22535), 'sklearn.model_selection.StratifiedKFold', 'StratifiedKFold', ([], {'n_splits': '(5)'}), '(n_splits=5)\n', (22523, 22535), False, 'from sklearn.model_selection import StratifiedKFold, cross_val_score, GridSearchCV, train_test_split\n'), ((23025, 23124), 'pandas.DataFrame', 'pd.DataFrame', (["{'Mean Log Loss': cv_means, 'Log Loss Std': cv_std, 'Algorithm':\n algorithm_names}"], {}), "({'Mean Log Loss': cv_means, 'Log Loss Std': cv_std,\n 'Algorithm': algorithm_names})\n", (23037, 23124), True, 'import pandas as pd\n'), ((23514, 23541), 'sklearn.model_selection.StratifiedKFold', 'StratifiedKFold', ([], {'n_splits': '(5)'}), '(n_splits=5)\n', (23529, 23541), False, 'from sklearn.model_selection import StratifiedKFold, cross_val_score, GridSearchCV, train_test_split\n'), ((24134, 24154), 'sklearn.linear_model.LogisticRegression', 'LogisticRegression', ([], {}), '()\n', (24152, 24154), False, 'from sklearn.linear_model import LogisticRegression, RidgeClassifier\n'), ((24156, 24189), 'sklearn.ensemble.RandomForestClassifier', 'ensemble.RandomForestClassifier', ([], {}), '()\n', (24187, 24189), False, 'from sklearn import svm, tree, linear_model, neighbors, naive_bayes, ensemble, discriminant_analysis, gaussian_process\n'), ((5103, 5121), 'pandas.concat', 'pd.concat', (['[df, v]'], {}), '([df, v])\n', (5112, 5121), True, 'import pandas as pd\n'), ((22629, 22696), 'sklearn.model_selection.cross_val_score', 'cross_val_score', (['classifier', 'X', 'y'], {'scoring': '"""neg_log_loss"""', 'cv': 'kfold'}), "(classifier, X, y, scoring='neg_log_loss', cv=kfold)\n", (22644, 22696), False, 'from sklearn.model_selection import StratifiedKFold, cross_val_score, GridSearchCV, train_test_split\n'), ((23653, 23738), 'sklearn.model_selection.GridSearchCV', 'GridSearchCV', (['alg'], {'param_grid': 'params', 'cv': 'kfold', 'scoring': '"""neg_log_loss"""', 'verbose': '(1)'}), "(alg, param_grid=params, cv=kfold, scoring='neg_log_loss',\n verbose=1)\n", (23665, 23738), False, 'from sklearn.model_selection import StratifiedKFold, cross_val_score, GridSearchCV, train_test_split\n'), ((1842, 1878), 'pandas.to_datetime', 'pd.to_datetime', (["df_all['match.date']"], {}), "(df_all['match.date'])\n", (1856, 1878), True, 'import pandas as pd\n'), ((26242, 26262), 'numpy.log2', 'np.log2', (['(p * (1 - p))'], {}), '(p * (1 - p))\n', (26249, 26262), True, 'import numpy as np\n'), ((26326, 26346), 'numpy.log2', 'np.log2', (['(p * (1 - p))'], {}), '(p * (1 - p))\n', (26333, 26346), True, 'import numpy as np\n'), ((26410, 26440), 'numpy.log2', 'np.log2', (['(orig_p * (1 - orig_p))'], {}), '(orig_p * (1 - orig_p))\n', (26417, 26440), True, 'import numpy as np\n'), ((26620, 26630), 'numpy.log2', 'np.log2', (['p'], {}), '(p)\n', (26627, 26630), True, 'import numpy as np\n'), ((26767, 26777), 'numpy.log2', 'np.log2', (['p'], {}), '(p)\n', (26774, 26777), True, 'import numpy as np\n'), ((26843, 26858), 'numpy.log2', 'np.log2', (['orig_p'], {}), '(orig_p)\n', (26850, 26858), True, 'import numpy as np\n'), ((26942, 26956), 'numpy.log2', 'np.log2', (['(1 - p)'], {}), '(1 - p)\n', (26949, 26956), True, 'import numpy as np\n'), ((27020, 27039), 'numpy.log2', 'np.log2', (['(1 - orig_p)'], {}), '(1 - orig_p)\n', (27027, 27039), True, 'import numpy as np\n'), ((27223, 27239), 'numpy.log2', 'np.log2', (['(1.0 - p)'], {}), '(1.0 - p)\n', (27230, 27239), True, 'import numpy as np\n'), ((27301, 27317), 'numpy.log2', 'np.log2', (['(1.0 - p)'], {}), '(1.0 - p)\n', (27308, 27317), True, 'import numpy as np\n'), ((27379, 27400), 'numpy.log2', 'np.log2', (['(1.0 - orig_p)'], {}), '(1.0 - orig_p)\n', (27386, 27400), True, 'import numpy as np\n'), ((4121, 4163), 'pandas.to_datetime', 'pd.to_datetime', (['df.Date'], {'format': '"""%Y-%m-%d"""'}), "(df.Date, format='%Y-%m-%d')\n", (4135, 4163), True, 'import pandas as pd\n')]
from keras.models import load_model from tensorflow import keras from matplotlib import pyplot as plt import numpy as np import _pickle as pickle import random #loads the test input with open('test_input.pickle', mode='rb') as f: test_input = pickle.load(f) with open('test_output.pickle', mode='rb') as f: test_output = pickle.load(f) #loads the model model = keras.models.load_model('model.h5') for i in range(4): #validates 4 times test_indices = random.choice(range(100)) #creates random indices to choose from the test dataset x = test_input[test_indices][0:100:3] #x is the former half y = test_input[test_indices][100:200:3] #y is the latter half sample_input = test_input[test_indices][np.newaxis, :] output = model.predict(sample_input) a, b, c = output[0] #predicts the coefficients #maps the coefficients to (x,y) coordinates predicted_x = np.arange(-1, 1, 2 / 1000) predicted_y = a* predicted_x**2 + b* predicted_x + c #creates subplots per each validation plt.subplot(220+(i+1)) plt.plot(x, y, 'x', label="desired output") plt.plot(predicted_x, predicted_y,label="prediction") plt.legend(loc = 'upper right') plt.xlabel('x') plt.ylabel('y') plt.ylim() plt.title('test'+str(i+1)) plt.savefig('eval.png', pad_inches=0.1) #saves the plot in png format. pad_inches is used to prevent the output png from having excess padding plt.show() #display the plot
[ "_pickle.load", "matplotlib.pyplot.subplot", "tensorflow.keras.models.load_model", "matplotlib.pyplot.show", "matplotlib.pyplot.plot", "matplotlib.pyplot.ylim", "matplotlib.pyplot.legend", "numpy.arange", "matplotlib.pyplot.ylabel", "matplotlib.pyplot.xlabel", "matplotlib.pyplot.savefig" ]
[((371, 406), 'tensorflow.keras.models.load_model', 'keras.models.load_model', (['"""model.h5"""'], {}), "('model.h5')\n", (394, 406), False, 'from tensorflow import keras\n'), ((1277, 1316), 'matplotlib.pyplot.savefig', 'plt.savefig', (['"""eval.png"""'], {'pad_inches': '(0.1)'}), "('eval.png', pad_inches=0.1)\n", (1288, 1316), True, 'from matplotlib import pyplot as plt\n'), ((1420, 1430), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (1428, 1430), True, 'from matplotlib import pyplot as plt\n'), ((248, 262), '_pickle.load', 'pickle.load', (['f'], {}), '(f)\n', (259, 262), True, 'import _pickle as pickle\n'), ((330, 344), '_pickle.load', 'pickle.load', (['f'], {}), '(f)\n', (341, 344), True, 'import _pickle as pickle\n'), ((895, 921), 'numpy.arange', 'np.arange', (['(-1)', '(1)', '(2 / 1000)'], {}), '(-1, 1, 2 / 1000)\n', (904, 921), True, 'import numpy as np\n'), ((1026, 1052), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(220 + (i + 1))'], {}), '(220 + (i + 1))\n', (1037, 1052), True, 'from matplotlib import pyplot as plt\n'), ((1053, 1096), 'matplotlib.pyplot.plot', 'plt.plot', (['x', 'y', '"""x"""'], {'label': '"""desired output"""'}), "(x, y, 'x', label='desired output')\n", (1061, 1096), True, 'from matplotlib import pyplot as plt\n'), ((1101, 1155), 'matplotlib.pyplot.plot', 'plt.plot', (['predicted_x', 'predicted_y'], {'label': '"""prediction"""'}), "(predicted_x, predicted_y, label='prediction')\n", (1109, 1155), True, 'from matplotlib import pyplot as plt\n'), ((1159, 1188), 'matplotlib.pyplot.legend', 'plt.legend', ([], {'loc': '"""upper right"""'}), "(loc='upper right')\n", (1169, 1188), True, 'from matplotlib import pyplot as plt\n'), ((1195, 1210), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""x"""'], {}), "('x')\n", (1205, 1210), True, 'from matplotlib import pyplot as plt\n'), ((1215, 1230), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""y"""'], {}), "('y')\n", (1225, 1230), True, 'from matplotlib import pyplot as plt\n'), ((1235, 1245), 'matplotlib.pyplot.ylim', 'plt.ylim', ([], {}), '()\n', (1243, 1245), True, 'from matplotlib import pyplot as plt\n')]
import argparse import os import gym import numpy as np from stable_baselines3.common.env_checker import check_env from stable_baselines3.common.noise import NormalActionNoise from stable_baselines3.common.utils import set_random_seed from stable_baselines3.sac import SAC from callback_buffer import CheckpointBufferCallback # Reference: https://stable-baselines3.readthedocs.io/en/master/guide/examples.html#multiprocessing-unleashing-the-power-of-vectorized-environments def make_env(env_id, rank, seed, radius, z_0, max_step, obs_size, eval, simple): """ Utility function for multiprocessed env. :param z_0: z_0 :param radius: [r_min, r_max] :param env_id: (str) the environment ID :param seed: (int) the inital seed for RNG :param rank: (int) index of the subprocess """ def _init(): env = gym.make(env_id, seed=seed, rank=rank, radius=radius, z_0=z_0, max_step=max_step, obs_size=obs_size, eval=eval, simple=simple) env.seed(seed + rank) return env set_random_seed(seed) return _init if __name__ == '__main__': parser = argparse.ArgumentParser() # data params parser.add_argument('-env_id', type=str, default='ADI-v0', choices='ADI-v0') parser.add_argument('-policy', type=str, default='cnn', choices='cnn') parser.add_argument('-global_seed', type=int, default=1) parser.add_argument('-max_envs_num', type=int, default=1) parser.add_argument('-batch_size', type=int, default=64) parser.add_argument('-r_max', type=float, default=-1.0) # -1.0 means we only allow run on a sphere parser.add_argument('-r_min', type=float, default=0.8) parser.add_argument('-z_0', type=float, default=0.35) parser.add_argument('-max_step', type=int, default=3) parser.add_argument('-obs_size', type=int, default=256) parser.add_argument('-buffer_size', type=int, default=10000) parser.add_argument('-total_timesteps', type=int, default=10000) parser.add_argument('-simple', action='store_true') opt = parser.parse_args() opt.eval = False opt.radius = [opt.r_min, opt.r_max] # Multiple env # env = SubprocVecEnv( # [make_env(opt.env_id, i, opt.global_seed, opt.radius, opt.z_0, opt.max_step, opt.obs_size) for i in range(opt.max_envs_num)]) # Single env env = make_env(opt.env_id, 0, opt.global_seed, opt.radius, opt.z_0, opt.max_step, opt.obs_size, opt.eval, opt.simple)() if opt.policy == 'cnn': policy_name = 'CnnPolicy' else: raise KeyError # Check env check_env(env) checkpoint_callback = CheckpointBufferCallback(save_freq=100, save_path='./logs/', name_prefix='checkpoint') n_actions = env.action_space.shape action_noise = NormalActionNoise(mean=np.zeros(n_actions), sigma=0.1 * np.ones(n_actions)) if os.path.isfile('./final_model_6b.zip'): print('Load model') model = SAC.load('./final_model_6b', tensorboard_log="./tb/", env=env) print(f'Current steps: {model.num_timesteps}') else: model = SAC(policy_name, env, verbose=1, buffer_size=opt.buffer_size, batch_size=opt.batch_size, train_freq=1, gradient_steps=3, tensorboard_log="./tb/", ent_coef='auto_0.7', action_noise=action_noise) print('Create new model') if os.path.isfile('./buffer_init.pkl'): print('Load Buffer') model.load_replay_buffer('./buffer_init') try: print('start learning') model._last_obs = None model.learn(total_timesteps=opt.total_timesteps, callback=checkpoint_callback, tb_log_name="simple", log_interval=3, reset_num_timesteps=False) finally: model.save('./final_model_inter') model.save_replay_buffer('./buffer_inter')
[ "argparse.ArgumentParser", "callback_buffer.CheckpointBufferCallback", "gym.make", "stable_baselines3.common.env_checker.check_env", "numpy.zeros", "numpy.ones", "stable_baselines3.common.utils.set_random_seed", "os.path.isfile", "stable_baselines3.sac.SAC", "stable_baselines3.sac.SAC.load" ]
[((1049, 1070), 'stable_baselines3.common.utils.set_random_seed', 'set_random_seed', (['seed'], {}), '(seed)\n', (1064, 1070), False, 'from stable_baselines3.common.utils import set_random_seed\n'), ((1130, 1155), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (1153, 1155), False, 'import argparse\n'), ((2595, 2609), 'stable_baselines3.common.env_checker.check_env', 'check_env', (['env'], {}), '(env)\n', (2604, 2609), False, 'from stable_baselines3.common.env_checker import check_env\n'), ((2637, 2728), 'callback_buffer.CheckpointBufferCallback', 'CheckpointBufferCallback', ([], {'save_freq': '(100)', 'save_path': '"""./logs/"""', 'name_prefix': '"""checkpoint"""'}), "(save_freq=100, save_path='./logs/', name_prefix=\n 'checkpoint')\n", (2661, 2728), False, 'from callback_buffer import CheckpointBufferCallback\n'), ((2868, 2906), 'os.path.isfile', 'os.path.isfile', (['"""./final_model_6b.zip"""'], {}), "('./final_model_6b.zip')\n", (2882, 2906), False, 'import os\n'), ((3352, 3387), 'os.path.isfile', 'os.path.isfile', (['"""./buffer_init.pkl"""'], {}), "('./buffer_init.pkl')\n", (3366, 3387), False, 'import os\n'), ((845, 976), 'gym.make', 'gym.make', (['env_id'], {'seed': 'seed', 'rank': 'rank', 'radius': 'radius', 'z_0': 'z_0', 'max_step': 'max_step', 'obs_size': 'obs_size', 'eval': 'eval', 'simple': 'simple'}), '(env_id, seed=seed, rank=rank, radius=radius, z_0=z_0, max_step=\n max_step, obs_size=obs_size, eval=eval, simple=simple)\n', (853, 976), False, 'import gym\n'), ((2952, 3014), 'stable_baselines3.sac.SAC.load', 'SAC.load', (['"""./final_model_6b"""'], {'tensorboard_log': '"""./tb/"""', 'env': 'env'}), "('./final_model_6b', tensorboard_log='./tb/', env=env)\n", (2960, 3014), False, 'from stable_baselines3.sac import SAC\n'), ((3096, 3298), 'stable_baselines3.sac.SAC', 'SAC', (['policy_name', 'env'], {'verbose': '(1)', 'buffer_size': 'opt.buffer_size', 'batch_size': 'opt.batch_size', 'train_freq': '(1)', 'gradient_steps': '(3)', 'tensorboard_log': '"""./tb/"""', 'ent_coef': '"""auto_0.7"""', 'action_noise': 'action_noise'}), "(policy_name, env, verbose=1, buffer_size=opt.buffer_size, batch_size=\n opt.batch_size, train_freq=1, gradient_steps=3, tensorboard_log='./tb/',\n ent_coef='auto_0.7', action_noise=action_noise)\n", (3099, 3298), False, 'from stable_baselines3.sac import SAC\n'), ((2807, 2826), 'numpy.zeros', 'np.zeros', (['n_actions'], {}), '(n_actions)\n', (2815, 2826), True, 'import numpy as np\n'), ((2840, 2858), 'numpy.ones', 'np.ones', (['n_actions'], {}), '(n_actions)\n', (2847, 2858), True, 'import numpy as np\n')]
# Import packages import time import numpy as np import pandas as pd from scipy.sparse import csr_matrix from scipy.sparse.linalg import eigsh ## Functions running netconf graph belief propagation # Adapted from Matlab script found at # https://github.com/dhivyaeswaran/dhivyaeswaran.github.io/tree/master/code ## Import numpy arrays from csv format def csvread(filename): return np.array(pd.read_csv(filename, header=None)) ## Transfer edges array to adjacency matrix (N*N (typically sparse)) def edges_to_adjmat(edges): n = np.max(edges)+1 # Get number of nodes edges = np.unique(np.append(edges,edges[:,[1,0]],axis=0),axis=0) edges = edges[edges[:,0]!=edges[:,1],:] adj_mat = csr_matrix((np.ones(len(edges[:,0])),(edges[:,0],edges[:,1])),shape=(n,n)).toarray() return adj_mat ## Run netConf belief propagation ## Input variables # edges - csv of # priors - N*k priors (set to 1/k..1/k for unseeded nodes) # mod - k*k modulation matrix # ep - 0.5 - ep/rho(A) is the modulation multiplier # stop - 0 - Defines fixed number of iterations # verbose - False - output loss for each iteration # max_iter - 100 - maximum iterations # limit - 1e-4 - loss threshold for early stop def netconf(edges,priors,mod=False, ep=0.5,stop=0,verbose=False,max_iter=100,limit=1e-4): # Define initial variables if verbose: print('Nodes: {}, Edges: {}'.format(len(priors),len(edges))) t = time.time() # Begin timing B, [N,k] = priors, priors.shape l, diff1 = np.zeros(N), 1 adj_mat = edges_to_adjmat(edges) v, D = np.abs(eigsh(adj_mat,1)[0][0]), np.diag(sum(adj_mat)) M = np.dot(np.divide(ep,v), mod if mod is not False else np.eye(priors.shape[1])) M1 = np.dot(M,np.linalg.pinv(np.eye(k)-np.dot(M,M))) M2 = np.dot(M,M1) # Add headers for verbose columns if verbose: print('It\tLoss\tLabel change\n') # Define number of iterations n_iter = max_iter if not stop else stop # Loop through iterations for i in range(n_iter-1): # Break when loss below limit when iterations not specified if not stop and diff1 < limit: if not verbose: print(i,' iterations') break # Update beliefs Bold, lold = B, l B = priors + np.dot(np.dot(adj_mat,B),M1) - np.dot(np.dot(D,B),M2) l = B.argmax(1) diff2 = np.sum(lold!=l) diff1 = np.max(np.abs(B-Bold)) if verbose: print('{}\t{:.5e}\t\t{}\n'.format(i,diff1,diff2)) # Return final beliefs and elapsed time if verbose: print('Time elapsed: {} seconds'.format(time.time()-t)) return B, time.time()-t
[ "numpy.divide", "numpy.sum", "numpy.eye", "numpy.abs", "pandas.read_csv", "numpy.zeros", "scipy.sparse.linalg.eigsh", "time.time", "numpy.append", "numpy.max", "numpy.dot" ]
[((1418, 1429), 'time.time', 'time.time', ([], {}), '()\n', (1427, 1429), False, 'import time\n'), ((1751, 1764), 'numpy.dot', 'np.dot', (['M', 'M1'], {}), '(M, M1)\n', (1757, 1764), True, 'import numpy as np\n'), ((394, 428), 'pandas.read_csv', 'pd.read_csv', (['filename'], {'header': 'None'}), '(filename, header=None)\n', (405, 428), True, 'import pandas as pd\n'), ((536, 549), 'numpy.max', 'np.max', (['edges'], {}), '(edges)\n', (542, 549), True, 'import numpy as np\n'), ((596, 638), 'numpy.append', 'np.append', (['edges', 'edges[:, [1, 0]]'], {'axis': '(0)'}), '(edges, edges[:, [1, 0]], axis=0)\n', (605, 638), True, 'import numpy as np\n'), ((1492, 1503), 'numpy.zeros', 'np.zeros', (['N'], {}), '(N)\n', (1500, 1503), True, 'import numpy as np\n'), ((1618, 1634), 'numpy.divide', 'np.divide', (['ep', 'v'], {}), '(ep, v)\n', (1627, 1634), True, 'import numpy as np\n'), ((2295, 2312), 'numpy.sum', 'np.sum', (['(lold != l)'], {}), '(lold != l)\n', (2301, 2312), True, 'import numpy as np\n'), ((1664, 1687), 'numpy.eye', 'np.eye', (['priors.shape[1]'], {}), '(priors.shape[1])\n', (1670, 1687), True, 'import numpy as np\n'), ((2330, 2346), 'numpy.abs', 'np.abs', (['(B - Bold)'], {}), '(B - Bold)\n', (2336, 2346), True, 'import numpy as np\n'), ((2539, 2550), 'time.time', 'time.time', ([], {}), '()\n', (2548, 2550), False, 'import time\n'), ((1720, 1729), 'numpy.eye', 'np.eye', (['k'], {}), '(k)\n', (1726, 1729), True, 'import numpy as np\n'), ((1730, 1742), 'numpy.dot', 'np.dot', (['M', 'M'], {}), '(M, M)\n', (1736, 1742), True, 'import numpy as np\n'), ((2247, 2259), 'numpy.dot', 'np.dot', (['D', 'B'], {}), '(D, B)\n', (2253, 2259), True, 'import numpy as np\n'), ((1558, 1575), 'scipy.sparse.linalg.eigsh', 'eigsh', (['adj_mat', '(1)'], {}), '(adj_mat, 1)\n', (1563, 1575), False, 'from scipy.sparse.linalg import eigsh\n'), ((2216, 2234), 'numpy.dot', 'np.dot', (['adj_mat', 'B'], {}), '(adj_mat, B)\n', (2222, 2234), True, 'import numpy as np\n'), ((2511, 2522), 'time.time', 'time.time', ([], {}), '()\n', (2520, 2522), False, 'import time\n')]
import abc import logging import dynesty import numpy as np import gbkfit.fitting.fitter import gbkfit.fitting.params from gbkfit.utils import parseutils log = logging.getLogger(__name__) def _prior_tansform_wrapper(theta): pass def _log_likelihood_wrapper(theta): pass class FitParameterDynesty(gbkfit.fitting.params.FitParam): @classmethod def load(cls, info): desc = f'fit parameter (class: {cls.__qualname__})' cls_args = parseutils.parse_options( info, desc, fun=cls.__init__, fun_rename_args=dict( initial='init', minimum='min', maximum='max')) return cls(**cls_args) def __init__(self, prior, periodic=None, reflective=None): pass class FitParamsDynesty(gbkfit.fitting.params.FitParams): @classmethod def load(cls, info, descs): return cls(info, descs) def __init__(self, params, descs, live_points=None): super().__init__(params, descs) class FitterDynesty(gbkfit.fitting.fitter.Fitter): def __init__(self): super().__init__() def _fit_impl(self, objective, parameters, interpreter): result1 = self._fit_impl_impl(objective, parameters, interpreter) result2 = result1 return result2 @abc.abstractmethod def _fit_impl_impl(self, objective, parameters, interpreter): pass class FitterDynestySNS(FitterDynesty): @staticmethod def type(): return 'dynesty.sns' @classmethod def load(cls, info): desc = '' opts = parseutils.parse_options_for_callable( info, desc, cls.__init__, fun_rename_args=dict( rstate='seed')) if 'rstate' in opts: opts['rstate'] = np.random.RandomState(opts['rstate']) return cls(**opts) def dump(self): return {'type': self.type(), **self._props} def __init__( self, # see dynesty.NestedSampler() nlive=500, bound='multi', sample='auto', update_interval=None, first_update=None, rstate=None, enlarge=None, bootstrap=0, vol_dec=0.5, vol_check=2.0, walks=25, facc=0.5, slices=5, fmove=0.9, max_move=100, # see dynesty.sampler.Sampler.run_nested() maxiter=None, maxcall=None, dlogz=None, logl_max=np.inf, n_effective=None, add_live=True, print_progress=True, print_func=None, save_bounds=True): super().__init__() self._props = locals() self._props.pop('self') self._props.pop('__class__') def _fit_impl_impl(self, objective, parameters, interpreter): ndim = 3 sampler = dynesty.NestedSampler( _log_likelihood_wrapper, _prior_tansform_wrapper, ndim, logl_args=(objective, interpreter), ptform_args=(), **self._props) result = sampler.run_nested() pass class FitterDynestyDNS(FitterDynesty): @staticmethod def type(): return 'dynesty.dns' @classmethod def load(cls, info): info['rstate'] = np.random.RandomState(info.get('seed')) cls_args = parseutils.parse_options(info, 'foo', fun=cls.__init__) return cls(**cls_args) def dump(self): return {'type': self.type(), **self._props} def __init__( self, # see dynesty.DynamicNestedSampler() bound='multi', sample='auto', update_interval=None, first_update=None, rstate=None, enlarge=None, bootstrap=0, vol_dec=0.5, vol_check=2.0, walks=25, facc=0.5, slices=5, fmove=0.9, max_move=100, # dynesty.dynamicsampler.DynamicNestedSampler.run_nested() nlive_init=500, maxiter_init=None, maxcall_init=None, dlogz_init=0.01, logl_max_init=np.inf, n_effective_init=np.inf, nlive_batch=500, wt_function=None, wt_kwargs=None, maxiter_batch=None, maxcall_batch=None, maxiter=None, maxcall=None, maxbatch=None, n_effective=np.inf, stop_function=None, stop_kwargs=None, use_stop=True, save_bounds=True, print_progress=True, print_func=None): super().__init__() self._props = locals() self._props.pop('self') self._props.pop('__class__') def _fit_impl(self, objective, param_info, param_interp, **kwargs): pass
[ "dynesty.NestedSampler", "gbkfit.utils.parseutils.parse_options", "numpy.random.RandomState", "logging.getLogger" ]
[((165, 192), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (182, 192), False, 'import logging\n'), ((2698, 2846), 'dynesty.NestedSampler', 'dynesty.NestedSampler', (['_log_likelihood_wrapper', '_prior_tansform_wrapper', 'ndim'], {'logl_args': '(objective, interpreter)', 'ptform_args': '()'}), '(_log_likelihood_wrapper, _prior_tansform_wrapper,\n ndim, logl_args=(objective, interpreter), ptform_args=(), **self._props)\n', (2719, 2846), False, 'import dynesty\n'), ((3181, 3236), 'gbkfit.utils.parseutils.parse_options', 'parseutils.parse_options', (['info', '"""foo"""'], {'fun': 'cls.__init__'}), "(info, 'foo', fun=cls.__init__)\n", (3205, 3236), False, 'from gbkfit.utils import parseutils\n'), ((1734, 1771), 'numpy.random.RandomState', 'np.random.RandomState', (["opts['rstate']"], {}), "(opts['rstate'])\n", (1755, 1771), True, 'import numpy as np\n')]
import itertools import os import sys # Add path to python source to path. sys.path.append(os.path.join( os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "python")) import SmoothParticleNets as spn import math import numpy as np import queue import torch import torch.autograd from gradcheck import gradcheck from regular_grid_interpolater import RegularGridInterpolator try: import pytest_args except ImportError: print("Make sure to compile SmoothParticleNets before running tests.") raise def construct_sdf(sdf_shape, nugget, width): scale = [1.0*width[i]/sdf_shape[i] for i in range(len(width))] ret = np.ones(sdf_shape, dtype=np.float32)*np.finfo(np.float32).max ret[nugget] = 0 return prop_sdf(ret, [(0, nugget)], scale=scale) def prop_sdf(sdf, initial_frontier, scale=[1, 1, 1]): sdf_shape = sdf.shape closed = set() frontier = queue.PriorityQueue() for c, p in initial_frontier: frontier.put((c, tuple(p))) while not frontier.empty(): cost, current = frontier.get() if current in closed: continue else: closed.add(current) for i in [-1, 0, 1]: if current[0] + i < 0 or current[0] + i >= sdf_shape[0]: continue for j in [-1, 0, 1]: if current[1] + j < 0 or current[1] + j >= sdf_shape[1]: continue for k in [-1, 0, 1]: if current[2] + k < 0 or current[2] + k >= sdf_shape[2]: continue if j == 0 and i == 0 and k == 0: continue nn = (current[0] + i, current[1] + j, current[2] + k) d = np.sqrt( np.sum(np.square([i*scale[0], j*scale[1], k*scale[2]]))) if cost + d < sdf[nn]: sdf[nn] = cost + d frontier.put((cost + d, nn)) return sdf def test_convsdf(): print("Testing CPU implementation of ConvSDF...") eval_convsdf(cuda=False) print("CPU implementation passed!") print("") if pytest_args.with_cuda: print("Testing CUDA implementation of ConvSDF...") eval_convsdf(cuda=True) print("CUDA implementation passed!") else: print("Not compiled with CUDA, skipping CUDA test.") def eval_convsdf(cuda=False): BATCH_SIZE = 2 N = 10 M = 30 NDIM = 3 KERNEL_SIZE = (3, 5, 3) DILATION = 0.001 NKERNELS = 2 MAX_DISTANCE = 13.37 M = 1 np.random.seed(0) locs = np.random.rand(BATCH_SIZE, N, NDIM) weights = np.random.rand(NKERNELS, np.prod(KERNEL_SIZE)) biases = np.random.rand(NKERNELS) kernel_centers = (np.array(KERNEL_SIZE) - 1)/2 ground_truth = np.zeros((BATCH_SIZE, N, NKERNELS), dtype=np.float32) sdf_widths = np.array([[4, 4, 4], [6, 4, 8], [5, 5, 5], ], dtype=np.float32)/1 sdf1 = construct_sdf((5, 5, 5), (1, 2, 3), sdf_widths[0, :]) sdf2 = construct_sdf((6, 4, 8), (1, 0, 2), sdf_widths[1, :]) sdf3 = construct_sdf((20, 20, 20), (5, 15, 5), sdf_widths[2, :]) sdfs = [sdf1, sdf2, sdf3] sdf_poses = np.random.rand(BATCH_SIZE, M, 7) sdf_poses[..., :3] -= 1.5 # Convert axis angle to quaternion sdf_poses[..., 3:-1] *= np.sin(sdf_poses[..., -1, np.newaxis]/2) sdf_poses[..., -1] = np.cos(sdf_poses[..., -1]/2) sdf_poses[..., 3:] /= np.sqrt((sdf_poses[..., 3:] ** 2).sum(axis=-1))[..., np.newaxis] idxs = np.random.randint(0, 3, size=(BATCH_SIZE, M)) idxs[-1, -1] = -1 scales = np.random.rand(BATCH_SIZE, M) + 0.5 sdf_fns = [RegularGridInterpolator( [np.linspace(0.5, y - 0.5, y)*s/y for y, s in zip(sdfs[i].shape, sdf_widths[i, ...])], sdfs[i], bounds_error=False, fill_value=np.finfo(np.float32).max) for i in range(len(sdfs))] for outk in range(NKERNELS): allkidx = itertools.product( *[list(range(-(k//2), k//2 + 1)) for k in KERNEL_SIZE[::-1]]) for k, kidx in enumerate(allkidx): for i in range(N): for b in range(BATCH_SIZE): r = locs[b, i, :] + [kidx[::-1][j] * DILATION for j in range(3)] minv = MAX_DISTANCE for m in range(M): mm = idxs[b, m] if mm < 0: continue r2 = quaternionMult(quaternionConjugate(sdf_poses[b, m, 3:]), quaternionMult(r - sdf_poses[b, m, :3], sdf_poses[b, m, 3:]))[:3] r2 /= scales[b, m] v = sdf_fns[mm](r2)*scales[b, m] minv = min(v, minv) ground_truth[b, i, outk] += weights[outk, k]*minv ground_truth += biases[np.newaxis, np.newaxis, :] def use_cuda(x): if cuda: return x.cuda() else: return x def undo_cuda(x): if cuda: return x.cpu() else: return x sdfs_t = [torch.FloatTensor(x) for x in sdfs] sdf_sizes_t = [np.mean([1.0*sdf_widths[i, j]/sdfs[i].shape[j] for j in range(len(sdfs[i].shape))]) for i in range(len(sdfs))] locs_t = torch.autograd.Variable( use_cuda(torch.FloatTensor(locs)), requires_grad=True) idxs_t = torch.autograd.Variable( use_cuda(torch.FloatTensor(idxs)), requires_grad=False) poses_t = torch.autograd.Variable(use_cuda(torch.FloatTensor(sdf_poses)), requires_grad=True) scales_t = torch.autograd.Variable(use_cuda(torch.FloatTensor(scales)), requires_grad=False) weights_t = torch.nn.Parameter( torch.FloatTensor(weights), requires_grad=True) biases_t = torch.nn.Parameter( torch.FloatTensor(biases), requires_grad=True) convsdf = spn.ConvSDF(sdfs_t, sdf_sizes_t, NKERNELS, NDIM, KERNEL_SIZE, DILATION, MAX_DISTANCE, compute_pose_grads=True) convsdf.weight = weights_t convsdf.bias = biases_t convsdf = use_cuda(convsdf) pred = undo_cuda(convsdf(locs_t, idxs_t, poses_t, scales_t)) np.testing.assert_array_almost_equal( pred.data.numpy(), ground_truth, decimal=3) # def func(l, w, b, pp): # _pp = torch.cat((pp, poses_t[..., -4:]), 2) # convsdf.weight = w # convsdf.bias = b # return (convsdf(l, idxs_t, _pp, scales_t),) # assert gradcheck(func, (locs_t, weights_t, biases_t, poses_t[..., :3]), eps=1e-2, atol=1e-3) # def func(pp): # # _pp = torch.cat((pp, poses_t[..., -4:]), 2) # return (convsdf(locs_t, idxs_t, pp, scales_t),) # assert gradcheck(func, (poses_t,), eps=1e-4, atol=1e-3) def func(l, w, b): convsdf.weight = w convsdf.bias = b return (convsdf(l, idxs_t, poses_t, scales_t),) assert torch.autograd.gradcheck(func, (locs_t, weights_t, biases_t), eps=1e-2, atol=1e-3, rtol=1e-1) test_2d_loc_grads() def test_2d_loc_grads(): sdfs = [torch.from_numpy( np.array([[0, 0.5], [0.5, 1]], dtype=np.float32)), ] convsdf = spn.ConvSDF(sdfs, [1, ], 1, 2, 1, 1, max_distance=1, with_params=False, compute_pose_grads=False) convsdf.weight.data.fill_(1) convsdf.bias.data.fill_(0) locs = [] for x in np.arange(0.51, 1.49, 2.0/100): for y in np.arange(0.51, 1.49, 2.0/100): locs.append([x, y]) locs_t = torch.autograd.Variable(torch.from_numpy(np.array([locs], dtype=np.float32)), requires_grad=True) idxs_t = torch.autograd.Variable( torch.from_numpy(np.array([[0]], dtype=np.float32))) poses_t = torch.autograd.Variable(torch.from_numpy( np.array([[[0, 0, 0]]], dtype=np.float32))) scales_t = torch.autograd.Variable( torch.from_numpy(np.array([[1]], dtype=np.float32))) def func(l): return (convsdf(l, idxs_t, poses_t, scales_t),) assert torch.autograd.gradcheck(func, (locs_t,), eps=1e-3, atol=1e-3) def quaternionMult(q1, q2): if len(q1) == 4: x1, y1, z1, w1 = q1 else: x1, y1, z1 = q1 w1 = 0 if len(q2) == 4: x2, y2, z2, w2 = q2 else: x2, y2, z2 = q2 w2 = 0 w = w1 * w2 - x1 * x2 - y1 * y2 - z1 * z2 x = w1 * x2 + x1 * w2 + y1 * z2 - z1 * y2 y = w1 * y2 + y1 * w2 + z1 * x2 - x1 * z2 z = w1 * z2 + z1 * w2 + x1 * y2 - y1 * x2 return np.array([x, y, z, w]) def quaternionConjugate(q): x, y, z, w = q return [-x, -y, -z, w] if __name__ == '__main__': test_convsdf()
[ "torch.autograd.gradcheck", "os.path.abspath", "numpy.random.seed", "numpy.square", "numpy.zeros", "numpy.ones", "torch.FloatTensor", "SmoothParticleNets.ConvSDF", "numpy.finfo", "numpy.sin", "numpy.random.randint", "numpy.arange", "numpy.cos", "numpy.array", "numpy.random.rand", "nump...
[((898, 919), 'queue.PriorityQueue', 'queue.PriorityQueue', ([], {}), '()\n', (917, 919), False, 'import queue\n'), ((2581, 2598), 'numpy.random.seed', 'np.random.seed', (['(0)'], {}), '(0)\n', (2595, 2598), True, 'import numpy as np\n'), ((2611, 2646), 'numpy.random.rand', 'np.random.rand', (['BATCH_SIZE', 'N', 'NDIM'], {}), '(BATCH_SIZE, N, NDIM)\n', (2625, 2646), True, 'import numpy as np\n'), ((2721, 2745), 'numpy.random.rand', 'np.random.rand', (['NKERNELS'], {}), '(NKERNELS)\n', (2735, 2745), True, 'import numpy as np\n'), ((2817, 2870), 'numpy.zeros', 'np.zeros', (['(BATCH_SIZE, N, NKERNELS)'], {'dtype': 'np.float32'}), '((BATCH_SIZE, N, NKERNELS), dtype=np.float32)\n', (2825, 2870), True, 'import numpy as np\n'), ((3282, 3314), 'numpy.random.rand', 'np.random.rand', (['BATCH_SIZE', 'M', '(7)'], {}), '(BATCH_SIZE, M, 7)\n', (3296, 3314), True, 'import numpy as np\n'), ((3412, 3454), 'numpy.sin', 'np.sin', (['(sdf_poses[..., -1, np.newaxis] / 2)'], {}), '(sdf_poses[..., -1, np.newaxis] / 2)\n', (3418, 3454), True, 'import numpy as np\n'), ((3478, 3508), 'numpy.cos', 'np.cos', (['(sdf_poses[..., -1] / 2)'], {}), '(sdf_poses[..., -1] / 2)\n', (3484, 3508), True, 'import numpy as np\n'), ((3645, 3690), 'numpy.random.randint', 'np.random.randint', (['(0)', '(3)'], {'size': '(BATCH_SIZE, M)'}), '(0, 3, size=(BATCH_SIZE, M))\n', (3662, 3690), True, 'import numpy as np\n'), ((6204, 6318), 'SmoothParticleNets.ConvSDF', 'spn.ConvSDF', (['sdfs_t', 'sdf_sizes_t', 'NKERNELS', 'NDIM', 'KERNEL_SIZE', 'DILATION', 'MAX_DISTANCE'], {'compute_pose_grads': '(True)'}), '(sdfs_t, sdf_sizes_t, NKERNELS, NDIM, KERNEL_SIZE, DILATION,\n MAX_DISTANCE, compute_pose_grads=True)\n', (6215, 6318), True, 'import SmoothParticleNets as spn\n'), ((7224, 7321), 'torch.autograd.gradcheck', 'torch.autograd.gradcheck', (['func', '(locs_t, weights_t, biases_t)'], {'eps': '(0.01)', 'atol': '(0.001)', 'rtol': '(0.1)'}), '(func, (locs_t, weights_t, biases_t), eps=0.01,\n atol=0.001, rtol=0.1)\n', (7248, 7321), False, 'import torch\n'), ((7511, 7610), 'SmoothParticleNets.ConvSDF', 'spn.ConvSDF', (['sdfs', '[1]', '(1)', '(2)', '(1)', '(1)'], {'max_distance': '(1)', 'with_params': '(False)', 'compute_pose_grads': '(False)'}), '(sdfs, [1], 1, 2, 1, 1, max_distance=1, with_params=False,\n compute_pose_grads=False)\n', (7522, 7610), True, 'import SmoothParticleNets as spn\n'), ((7726, 7758), 'numpy.arange', 'np.arange', (['(0.51)', '(1.49)', '(2.0 / 100)'], {}), '(0.51, 1.49, 2.0 / 100)\n', (7735, 7758), True, 'import numpy as np\n'), ((8380, 8444), 'torch.autograd.gradcheck', 'torch.autograd.gradcheck', (['func', '(locs_t,)'], {'eps': '(0.001)', 'atol': '(0.001)'}), '(func, (locs_t,), eps=0.001, atol=0.001)\n', (8404, 8444), False, 'import torch\n'), ((8864, 8886), 'numpy.array', 'np.array', (['[x, y, z, w]'], {}), '([x, y, z, w])\n', (8872, 8886), True, 'import numpy as np\n'), ((647, 683), 'numpy.ones', 'np.ones', (['sdf_shape'], {'dtype': 'np.float32'}), '(sdf_shape, dtype=np.float32)\n', (654, 683), True, 'import numpy as np\n'), ((2686, 2706), 'numpy.prod', 'np.prod', (['KERNEL_SIZE'], {}), '(KERNEL_SIZE)\n', (2693, 2706), True, 'import numpy as np\n'), ((2889, 2950), 'numpy.array', 'np.array', (['[[4, 4, 4], [6, 4, 8], [5, 5, 5]]'], {'dtype': 'np.float32'}), '([[4, 4, 4], [6, 4, 8], [5, 5, 5]], dtype=np.float32)\n', (2897, 2950), True, 'import numpy as np\n'), ((3726, 3755), 'numpy.random.rand', 'np.random.rand', (['BATCH_SIZE', 'M'], {}), '(BATCH_SIZE, M)\n', (3740, 3755), True, 'import numpy as np\n'), ((5338, 5358), 'torch.FloatTensor', 'torch.FloatTensor', (['x'], {}), '(x)\n', (5355, 5358), False, 'import torch\n'), ((6051, 6077), 'torch.FloatTensor', 'torch.FloatTensor', (['weights'], {}), '(weights)\n', (6068, 6077), False, 'import torch\n'), ((6142, 6167), 'torch.FloatTensor', 'torch.FloatTensor', (['biases'], {}), '(biases)\n', (6159, 6167), False, 'import torch\n'), ((7775, 7807), 'numpy.arange', 'np.arange', (['(0.51)', '(1.49)', '(2.0 / 100)'], {}), '(0.51, 1.49, 2.0 / 100)\n', (7784, 7807), True, 'import numpy as np\n'), ((684, 704), 'numpy.finfo', 'np.finfo', (['np.float32'], {}), '(np.float32)\n', (692, 704), True, 'import numpy as np\n'), ((2769, 2790), 'numpy.array', 'np.array', (['KERNEL_SIZE'], {}), '(KERNEL_SIZE)\n', (2777, 2790), True, 'import numpy as np\n'), ((5587, 5610), 'torch.FloatTensor', 'torch.FloatTensor', (['locs'], {}), '(locs)\n', (5604, 5610), False, 'import torch\n'), ((5688, 5711), 'torch.FloatTensor', 'torch.FloatTensor', (['idxs'], {}), '(idxs)\n', (5705, 5711), False, 'import torch\n'), ((5782, 5810), 'torch.FloatTensor', 'torch.FloatTensor', (['sdf_poses'], {}), '(sdf_poses)\n', (5799, 5810), False, 'import torch\n'), ((5919, 5944), 'torch.FloatTensor', 'torch.FloatTensor', (['scales'], {}), '(scales)\n', (5936, 5944), False, 'import torch\n'), ((7444, 7492), 'numpy.array', 'np.array', (['[[0, 0.5], [0.5, 1]]'], {'dtype': 'np.float32'}), '([[0, 0.5], [0.5, 1]], dtype=np.float32)\n', (7452, 7492), True, 'import numpy as np\n'), ((7893, 7927), 'numpy.array', 'np.array', (['[locs]'], {'dtype': 'np.float32'}), '([locs], dtype=np.float32)\n', (7901, 7927), True, 'import numpy as np\n'), ((8050, 8083), 'numpy.array', 'np.array', (['[[0]]'], {'dtype': 'np.float32'}), '([[0]], dtype=np.float32)\n', (8058, 8083), True, 'import numpy as np\n'), ((8150, 8191), 'numpy.array', 'np.array', (['[[[0, 0, 0]]]'], {'dtype': 'np.float32'}), '([[[0, 0, 0]]], dtype=np.float32)\n', (8158, 8191), True, 'import numpy as np\n'), ((8259, 8292), 'numpy.array', 'np.array', (['[[1]]'], {'dtype': 'np.float32'}), '([[1]], dtype=np.float32)\n', (8267, 8292), True, 'import numpy as np\n'), ((143, 168), 'os.path.abspath', 'os.path.abspath', (['__file__'], {}), '(__file__)\n', (158, 168), False, 'import os\n'), ((3955, 3975), 'numpy.finfo', 'np.finfo', (['np.float32'], {}), '(np.float32)\n', (3963, 3975), True, 'import numpy as np\n'), ((3812, 3840), 'numpy.linspace', 'np.linspace', (['(0.5)', '(y - 0.5)', 'y'], {}), '(0.5, y - 0.5, y)\n', (3823, 3840), True, 'import numpy as np\n'), ((1787, 1840), 'numpy.square', 'np.square', (['[i * scale[0], j * scale[1], k * scale[2]]'], {}), '([i * scale[0], j * scale[1], k * scale[2]])\n', (1796, 1840), True, 'import numpy as np\n')]
""" This file implements some ensemble classifiers. Some algorithms may not work well beacause they are implemented during my early work, including CalibratedLabelRanking and RandomKLabelsets. """ import numpy as np import copy import math import random from sklearn.multiclass import OneVsRestClassifier from scipy.sparse import csr_matrix, hstack, vstack from sklearn.neighbors import NearestNeighbors class BinaryRelevance: # A simple wrapper for OneVsRestClassifier def __init__(self, estimator): self.classifier = OneVsRestClassifier(estimator) def fit(self, X, y): self.classifier.fit(X, y) return self def predict(self, X): binary_result = self.classifier.predict(X) sample_num, classes = binary_result.shape y_reverse = [] for i in range(sample_num): sample_label = [j for j in range(classes) if binary_result[i][j] == 1] y_reverse.append(sample_label) return y_reverse class ClassifierChains: def __init__(self, estimator): self.estimator = estimator self.estimators = [] self.classes = 0 def fit(self, X, y): self.estimators = [] self.classes = y.shape[1] for i in range(self.classes): temp_column = y[:, i] temp_estimator = copy.deepcopy(self.estimator).fit(X, temp_column) self.estimators.append(temp_estimator) temp_column = np.array([temp_column.tolist()]) temp_column = csr_matrix(temp_column.T) X = hstack([X, temp_column]) return self def predict(self, X): result = [] dataset_length = X.shape[0] class_num = len(self.estimators) # Initialize result array for i in range(dataset_length): result.append([]) for j in range(class_num): temp_result = self.estimators[j].predict(X) for k in range(dataset_length): if temp_result[k] == 1.0: result[k].append(j) temp_result = np.array([temp_result]).T.tolist() temp_result = csr_matrix(temp_result) X = hstack([X, temp_result]) return result class CalibratedLabelRanking: def __init__(self, estimator): self.estimator = estimator def fit(self, X, y): self.estimators_ = [] self.samples = y.shape[0] self.classes_ = y.shape[1] self.virtual_label = self.classes_ for i in range(0, self.classes_): for j in range(i + 1, self.classes_): temp_estimator = copy.deepcopy(self.estimator) data = None target = [] y_i = y[:, i] y_j = y[:, j] for index in range(self.samples): if y_i[index] + y_j[index] == 1: data = vstack([data, X.getrow(index)]) if data is not None else X.getrow(index) target.append(i if y_i[index] == 1 else j) if target.count(target[0]) == len(target) or len(target) == 0: continue self.estimators_.append(temp_estimator.fit(data, target)) for i in range(0, self.classes_): target = [] temp_estimator = copy.deepcopy(self.estimator) y_i = y[:, i] for index in range(self.samples): target.append(i if y_i[index] == 1 else self.virtual_label) if target.count(target[0]) == len(target) or len(target) == 0: continue self.estimators_.append(temp_estimator.fit(X, target)) return self def predict(self, X): test_samples = X.shape[0] count = [{} for i in range(test_samples)] for estimator_ in self.estimators_: res = estimator_.predict(X) for i in range(test_samples): tmp = res[i] if tmp in count[i]: count[i][tmp] += 1 else: count[i][tmp] = 1 result = [] for single_count in count: one_res = [] threshold = single_count[self.virtual_label] if self.virtual_label in single_count else 0 for entry in single_count: if single_count[entry] > threshold: one_res.append(entry) result.append(sorted(one_res)) return result class RandomKLabelsets: def __init__(self, estimator): self.estimator = estimator def fit(self, X, y): self.classes_ = y.shape[1] self.samples = y.shape[0] self.maps = [] self.estimators_ = [] # TODO:k should be changed k = 3 n = 2 * self.classes_ labels = [i for i in range(self.classes_)] self.k_labelsets = [] for i in range(n): labelset = sorted(random.sample(labels, k)) while labelset in self.k_labelsets: labelset = sorted(random.sample(labels, k)) self.k_labelsets.append(labelset) # Reverse Multilabel Minarization y_reverse = [] for i in range(self.samples): sample_label = [j for j in range(self.classes_) if y[i][j] == 1] y_reverse.append(sample_label) for each_set in self.k_labelsets: temp_estimator = copy.deepcopy(self.estimator) class_map = [] data = None target = [] for index in range(self.samples): intersection = [x for x in y_reverse[index] if x in each_set] if len(intersection) == 0: continue if intersection not in class_map: class_map.append(intersection) target.append(class_map.index(intersection)) data = vstack([data, X.getrow(index)]) if data is not None else X.getrow(index) self.maps.append(class_map) self.estimators_.append(temp_estimator.fit(data, target)) return self def predict(self, X): test_samples = X.shape[0] result = [{} for i in range(test_samples)] max_votes = [0 for i in range(self.classes_)] for labelset in self.k_labelsets: for index in labelset: max_votes[index] += 1 for estimator_id in range(len(self.estimators_)): estimator = self.estimators_[estimator_id] res = estimator.predict(X) for index in range(test_samples): actual_res = self.maps[estimator_id][res[index]] for label in actual_res: if label in result[index]: result[index][label] += 1 else: result[index][label] = 1 return_result = [] for each_result in result: label_result = [] for i in each_result: if each_result[i] / max_votes[i] > 0.5: label_result.append(i) return_result.append(label_result) return return_result class MLKNN: def __init__(self, k): self.knn = None self.samples = 0 self.classes = 0 self.k = k self.y = None self.s = 1 self.ph = None self.kj = None self.knj = None def fit(self, X, y): X = csr_matrix(X) self.samples = y.shape[0] self.classes = y.shape[1] self.knn = NearestNeighbors(self.k) self.knn.fit(X) self.ph = np.sum(y, axis=0) # Reverse multilabel minarization and prepare for P(Hj) y_reverse = [] for i in range(self.samples): sample_label = [j for j in range(self.classes) if y[i][j] == 1] y_reverse.append(sample_label) self.y = y_reverse self.ph = (self.s + self.ph) / (2 * self.s + self.samples) self.ph /= 1 - self.ph self.kj = np.zeros((self.classes, self.k + 1)) self.knj = np.zeros((self.classes, self.k + 1)) for index in range(self.samples): sample_label = y_reverse[index] neighbors = self.knn.kneighbors(X.getrow(index), n_neighbors=self.k + 1, return_distance=False)[0][1:] neighbor_label_count = [0 for i in range(self.classes)] for neighbor in neighbors: neighbor_label = y_reverse[neighbor] for each_label in neighbor_label: neighbor_label_count[each_label] += 1 for label_index in range(self.classes): if label_index in sample_label: self.kj[label_index][neighbor_label_count[label_index]] += 1 else: self.knj[label_index][neighbor_label_count[label_index]] += 1 return self def predict(self, X): X = csr_matrix(X) test_samples_length = X.shape[0] res = [[] for i in range(test_samples_length)] for index in range(test_samples_length): neighbors = self.knn.kneighbors(X.getrow(index), n_neighbors=self.k + 1, return_distance=False)[0][1:] neighbor_label_count = [0 for i in range(self.classes)] for neighbor in neighbors: neighbor_label = self.y[neighbor] for each_label in neighbor_label: neighbor_label_count[each_label] += 1 for each_label in range(self.classes): pch = (self.s + self.kj[each_label][neighbor_label_count[each_label]]) / ( self.s * (self.k + 1) + sum(self.kj[each_label])) pcnh = (self.s + self.knj[each_label][neighbor_label_count[each_label]]) / ( self.s * (self.k + 1) + sum(self.knj[each_label])) probability = self.ph[each_label] * pch / pcnh if probability > 1: res[index].append(each_label) return res
[ "copy.deepcopy", "numpy.sum", "random.sample", "numpy.zeros", "scipy.sparse.csr_matrix", "sklearn.neighbors.NearestNeighbors", "sklearn.multiclass.OneVsRestClassifier", "numpy.array", "scipy.sparse.hstack" ]
[((538, 568), 'sklearn.multiclass.OneVsRestClassifier', 'OneVsRestClassifier', (['estimator'], {}), '(estimator)\n', (557, 568), False, 'from sklearn.multiclass import OneVsRestClassifier\n'), ((7442, 7455), 'scipy.sparse.csr_matrix', 'csr_matrix', (['X'], {}), '(X)\n', (7452, 7455), False, 'from scipy.sparse import csr_matrix, hstack, vstack\n'), ((7543, 7567), 'sklearn.neighbors.NearestNeighbors', 'NearestNeighbors', (['self.k'], {}), '(self.k)\n', (7559, 7567), False, 'from sklearn.neighbors import NearestNeighbors\n'), ((7611, 7628), 'numpy.sum', 'np.sum', (['y'], {'axis': '(0)'}), '(y, axis=0)\n', (7617, 7628), True, 'import numpy as np\n'), ((8018, 8054), 'numpy.zeros', 'np.zeros', (['(self.classes, self.k + 1)'], {}), '((self.classes, self.k + 1))\n', (8026, 8054), True, 'import numpy as np\n'), ((8074, 8110), 'numpy.zeros', 'np.zeros', (['(self.classes, self.k + 1)'], {}), '((self.classes, self.k + 1))\n', (8082, 8110), True, 'import numpy as np\n'), ((8927, 8940), 'scipy.sparse.csr_matrix', 'csr_matrix', (['X'], {}), '(X)\n', (8937, 8940), False, 'from scipy.sparse import csr_matrix, hstack, vstack\n'), ((1513, 1538), 'scipy.sparse.csr_matrix', 'csr_matrix', (['temp_column.T'], {}), '(temp_column.T)\n', (1523, 1538), False, 'from scipy.sparse import csr_matrix, hstack, vstack\n'), ((1555, 1579), 'scipy.sparse.hstack', 'hstack', (['[X, temp_column]'], {}), '([X, temp_column])\n', (1561, 1579), False, 'from scipy.sparse import csr_matrix, hstack, vstack\n'), ((2136, 2159), 'scipy.sparse.csr_matrix', 'csr_matrix', (['temp_result'], {}), '(temp_result)\n', (2146, 2159), False, 'from scipy.sparse import csr_matrix, hstack, vstack\n'), ((2177, 2201), 'scipy.sparse.hstack', 'hstack', (['[X, temp_result]'], {}), '([X, temp_result])\n', (2183, 2201), False, 'from scipy.sparse import csr_matrix, hstack, vstack\n'), ((3320, 3349), 'copy.deepcopy', 'copy.deepcopy', (['self.estimator'], {}), '(self.estimator)\n', (3333, 3349), False, 'import copy\n'), ((5405, 5434), 'copy.deepcopy', 'copy.deepcopy', (['self.estimator'], {}), '(self.estimator)\n', (5418, 5434), False, 'import copy\n'), ((2621, 2650), 'copy.deepcopy', 'copy.deepcopy', (['self.estimator'], {}), '(self.estimator)\n', (2634, 2650), False, 'import copy\n'), ((4929, 4953), 'random.sample', 'random.sample', (['labels', 'k'], {}), '(labels, k)\n', (4942, 4953), False, 'import random\n'), ((1327, 1356), 'copy.deepcopy', 'copy.deepcopy', (['self.estimator'], {}), '(self.estimator)\n', (1340, 1356), False, 'import copy\n'), ((5037, 5061), 'random.sample', 'random.sample', (['labels', 'k'], {}), '(labels, k)\n', (5050, 5061), False, 'import random\n'), ((2075, 2098), 'numpy.array', 'np.array', (['[temp_result]'], {}), '([temp_result])\n', (2083, 2098), True, 'import numpy as np\n')]
import numpy as np import os import torch import random from bert_serving.client import BertClient random.seed(31415926) def build_imdb_npy(imdb_path): for file_path in [os.path.join(imdb_path, "train"), os.path.join(imdb_path, "test")]: txt_list = [] y = [] for label in ["pos", "neg"]: train_path = os.path.join(file_path, label) for fname in os.listdir(train_path): f = open(os.path.join(train_path, fname)) txt = "" for l in f.readlines(): txt += (l + " ") txt_list.append(txt) if label == "pos": y.append(1) else: y.append(0) y = np.array(y) bc = BertClient() res = bc.encode(txt_list) np.save(os.path.join(file_path, "bert_large_encode_res.npy"), res) np.save(os.path.join(file_path, "y.npy"), y) # res = np.load(os.path.join(file_path, "all_bert_fine_tuning_encode_res.npy")) # y = np.load(os.path.join(file_path, "all_y.npy")) topic_dic = dict() lines = [] f = open(os.path.join(file_path, "urls_pos.txt")) lines.extend([x[26:35] for x in f.readlines()]) f = open(os.path.join(file_path, "urls_neg.txt")) lines.extend([x[26:35] for x in f.readlines()]) s_edge = [] s_bug_edge = [] s_be = [] s_y = [] t_idx = 0 for idx, id in enumerate(lines): if id not in topic_dic: topic_dic[id] = len(topic_dic) s_edge.append([]) s_bug_edge.append([]) s_be.append([res[idx]]) s_y.append([y[idx]]) # t_idx += 1 else: t_idx = topic_dic[id] new_idx = len(s_be[t_idx]) for i in range(len(s_be[t_idx])): s_edge[t_idx].append([i, new_idx]) s_edge[t_idx].append([new_idx, i]) s_bug_edge[t_idx].append([0, new_idx]) s_bug_edge[t_idx].append([new_idx, 0]) s_be[t_idx].append(res[idx]) s_y[t_idx].append(y[idx]) np.save(os.path.join(file_path, "split_bert_large_encode_res.npy"), s_be) np.save(os.path.join(file_path, "split_edge.npy"), s_edge) np.save(os.path.join(file_path, "split_bug_edge.npy"), s_bug_edge) np.save(os.path.join(file_path, "split_y.npy"), s_y) def load_data(filepath): bert_encode_res = np.load(os.path.join(filepath, "split_bert_large_encode_res.npy"),allow_pickle=True) # 25000,768 y = np.load(os.path.join(filepath, "split_y.npy"),allow_pickle=True) # 25000 edge = np.load(os.path.join(filepath, "split_edge.npy"),allow_pickle=True) # 2,edge_num*2 bug_edge = np.load(os.path.join(filepath, "split_bug_edge.npy"),allow_pickle=True) # 2,edge_num*2 datas = [] for x, y, e, eb in zip(bert_encode_res, y, edge, bug_edge): x = np.array([_.tolist() for _ in x], dtype=np.float) y = np.array(y, dtype=np.long) if len(e) == 0: e = np.empty((0, 2), dtype=np.long).transpose() eb = np.empty((0, 2), dtype=np.long).transpose() else: e = np.array(e).transpose() eb = np.array(eb).transpose() datas.append((x, y, e, eb)) random.shuffle(datas) max_node_num = 2000 def empty(): x = np.empty((0, 1024), dtype=np.float) y = np.empty(0, dtype=np.long) e = np.empty((0, 2), dtype=np.long).transpose() eb = np.empty((0, 2), dtype=np.long).transpose() return x, y, e, eb new_res = [] n_x, n_y, n_e, n_eb = empty() for x, y, e, eb in datas: if len(n_x) + len(x) > max_node_num: new_res.append((n_x, n_y, n_e, n_eb)) n_x, n_y, n_e, n_eb = empty() if len(e) > 0: e = e + len(n_x) eb = eb + len(n_x) n_e = np.concatenate((n_e, e), axis=1) n_eb = np.concatenate((n_eb, eb), axis=1) n_x = np.concatenate((n_x, x), axis=0) n_y = np.concatenate((n_y, y), axis=0) if len(n_x) > 0: new_res.append((n_x, n_y, n_e, n_eb)) # print(new_res) xx = [] yy = [] ee = [] eebb = [] for x, y, e, eb in new_res: xx.append(x) yy.append(y) ee.append(e.transpose()) eebb.append(eb.transpose()) np.save(os.path.join(filepath, "split_2k_bert_large_encode_res.npy"), xx) np.save(os.path.join(filepath, "split_2k_edge.npy"), ee) np.save(os.path.join(filepath, "split_2k_bug_edge.npy"), eebb) np.save(os.path.join(filepath, "split_2k_y.npy"), yy) imdb_path = "/mnt/nas1/NLP/public_dataset/TC/imdb/aclImdb" build_imdb_npy(imdb_path) load_data(os.path.join(imdb_path,"train")) load_data(os.path.join(imdb_path,"test"))
[ "random.shuffle", "numpy.empty", "numpy.array", "random.seed", "bert_serving.client.BertClient", "os.path.join", "os.listdir", "numpy.concatenate" ]
[((100, 121), 'random.seed', 'random.seed', (['(31415926)'], {}), '(31415926)\n', (111, 121), False, 'import random\n'), ((3431, 3452), 'random.shuffle', 'random.shuffle', (['datas'], {}), '(datas)\n', (3445, 3452), False, 'import random\n'), ((4865, 4897), 'os.path.join', 'os.path.join', (['imdb_path', '"""train"""'], {}), "(imdb_path, 'train')\n", (4877, 4897), False, 'import os\n'), ((4908, 4939), 'os.path.join', 'os.path.join', (['imdb_path', '"""test"""'], {}), "(imdb_path, 'test')\n", (4920, 4939), False, 'import os\n'), ((176, 208), 'os.path.join', 'os.path.join', (['imdb_path', '"""train"""'], {}), "(imdb_path, 'train')\n", (188, 208), False, 'import os\n'), ((232, 263), 'os.path.join', 'os.path.join', (['imdb_path', '"""test"""'], {}), "(imdb_path, 'test')\n", (244, 263), False, 'import os\n'), ((776, 787), 'numpy.array', 'np.array', (['y'], {}), '(y)\n', (784, 787), True, 'import numpy as np\n'), ((801, 813), 'bert_serving.client.BertClient', 'BertClient', ([], {}), '()\n', (811, 813), False, 'from bert_serving.client import BertClient\n'), ((2599, 2656), 'os.path.join', 'os.path.join', (['filepath', '"""split_bert_large_encode_res.npy"""'], {}), "(filepath, 'split_bert_large_encode_res.npy')\n", (2611, 2656), False, 'import os\n'), ((2705, 2742), 'os.path.join', 'os.path.join', (['filepath', '"""split_y.npy"""'], {}), "(filepath, 'split_y.npy')\n", (2717, 2742), False, 'import os\n'), ((2790, 2830), 'os.path.join', 'os.path.join', (['filepath', '"""split_edge.npy"""'], {}), "(filepath, 'split_edge.npy')\n", (2802, 2830), False, 'import os\n'), ((2889, 2933), 'os.path.join', 'os.path.join', (['filepath', '"""split_bug_edge.npy"""'], {}), "(filepath, 'split_bug_edge.npy')\n", (2901, 2933), False, 'import os\n'), ((3122, 3148), 'numpy.array', 'np.array', (['y'], {'dtype': 'np.long'}), '(y, dtype=np.long)\n', (3130, 3148), True, 'import numpy as np\n'), ((3508, 3543), 'numpy.empty', 'np.empty', (['(0, 1024)'], {'dtype': 'np.float'}), '((0, 1024), dtype=np.float)\n', (3516, 3543), True, 'import numpy as np\n'), ((3556, 3582), 'numpy.empty', 'np.empty', (['(0)'], {'dtype': 'np.long'}), '(0, dtype=np.long)\n', (3564, 3582), True, 'import numpy as np\n'), ((4144, 4176), 'numpy.concatenate', 'np.concatenate', (['(n_x, x)'], {'axis': '(0)'}), '((n_x, x), axis=0)\n', (4158, 4176), True, 'import numpy as np\n'), ((4191, 4223), 'numpy.concatenate', 'np.concatenate', (['(n_y, y)'], {'axis': '(0)'}), '((n_y, y), axis=0)\n', (4205, 4223), True, 'import numpy as np\n'), ((4517, 4577), 'os.path.join', 'os.path.join', (['filepath', '"""split_2k_bert_large_encode_res.npy"""'], {}), "(filepath, 'split_2k_bert_large_encode_res.npy')\n", (4529, 4577), False, 'import os\n'), ((4595, 4638), 'os.path.join', 'os.path.join', (['filepath', '"""split_2k_edge.npy"""'], {}), "(filepath, 'split_2k_edge.npy')\n", (4607, 4638), False, 'import os\n'), ((4656, 4703), 'os.path.join', 'os.path.join', (['filepath', '"""split_2k_bug_edge.npy"""'], {}), "(filepath, 'split_2k_bug_edge.npy')\n", (4668, 4703), False, 'import os\n'), ((4723, 4763), 'os.path.join', 'os.path.join', (['filepath', '"""split_2k_y.npy"""'], {}), "(filepath, 'split_2k_y.npy')\n", (4735, 4763), False, 'import os\n'), ((365, 395), 'os.path.join', 'os.path.join', (['file_path', 'label'], {}), '(file_path, label)\n', (377, 395), False, 'import os\n'), ((422, 444), 'os.listdir', 'os.listdir', (['train_path'], {}), '(train_path)\n', (432, 444), False, 'import os\n'), ((865, 917), 'os.path.join', 'os.path.join', (['file_path', '"""bert_large_encode_res.npy"""'], {}), "(file_path, 'bert_large_encode_res.npy')\n", (877, 917), False, 'import os\n'), ((940, 972), 'os.path.join', 'os.path.join', (['file_path', '"""y.npy"""'], {}), "(file_path, 'y.npy')\n", (952, 972), False, 'import os\n'), ((1190, 1229), 'os.path.join', 'os.path.join', (['file_path', '"""urls_pos.txt"""'], {}), "(file_path, 'urls_pos.txt')\n", (1202, 1229), False, 'import os\n'), ((1304, 1343), 'os.path.join', 'os.path.join', (['file_path', '"""urls_neg.txt"""'], {}), "(file_path, 'urls_neg.txt')\n", (1316, 1343), False, 'import os\n'), ((2274, 2332), 'os.path.join', 'os.path.join', (['file_path', '"""split_bert_large_encode_res.npy"""'], {}), "(file_path, 'split_bert_large_encode_res.npy')\n", (2286, 2332), False, 'import os\n'), ((2356, 2397), 'os.path.join', 'os.path.join', (['file_path', '"""split_edge.npy"""'], {}), "(file_path, 'split_edge.npy')\n", (2368, 2397), False, 'import os\n'), ((2423, 2468), 'os.path.join', 'os.path.join', (['file_path', '"""split_bug_edge.npy"""'], {}), "(file_path, 'split_bug_edge.npy')\n", (2435, 2468), False, 'import os\n'), ((2498, 2536), 'os.path.join', 'os.path.join', (['file_path', '"""split_y.npy"""'], {}), "(file_path, 'split_y.npy')\n", (2510, 2536), False, 'import os\n'), ((4043, 4075), 'numpy.concatenate', 'np.concatenate', (['(n_e, e)'], {'axis': '(1)'}), '((n_e, e), axis=1)\n', (4057, 4075), True, 'import numpy as np\n'), ((4095, 4129), 'numpy.concatenate', 'np.concatenate', (['(n_eb, eb)'], {'axis': '(1)'}), '((n_eb, eb), axis=1)\n', (4109, 4129), True, 'import numpy as np\n'), ((3595, 3626), 'numpy.empty', 'np.empty', (['(0, 2)'], {'dtype': 'np.long'}), '((0, 2), dtype=np.long)\n', (3603, 3626), True, 'import numpy as np\n'), ((3652, 3683), 'numpy.empty', 'np.empty', (['(0, 2)'], {'dtype': 'np.long'}), '((0, 2), dtype=np.long)\n', (3660, 3683), True, 'import numpy as np\n'), ((471, 502), 'os.path.join', 'os.path.join', (['train_path', 'fname'], {}), '(train_path, fname)\n', (483, 502), False, 'import os\n'), ((3190, 3221), 'numpy.empty', 'np.empty', (['(0, 2)'], {'dtype': 'np.long'}), '((0, 2), dtype=np.long)\n', (3198, 3221), True, 'import numpy as np\n'), ((3251, 3282), 'numpy.empty', 'np.empty', (['(0, 2)'], {'dtype': 'np.long'}), '((0, 2), dtype=np.long)\n', (3259, 3282), True, 'import numpy as np\n'), ((3325, 3336), 'numpy.array', 'np.array', (['e'], {}), '(e)\n', (3333, 3336), True, 'import numpy as np\n'), ((3366, 3378), 'numpy.array', 'np.array', (['eb'], {}), '(eb)\n', (3374, 3378), True, 'import numpy as np\n')]
#Batch Input Logic with multiple layers import numpy as np np.random.seed(0) X = [[1, 2, 3, 2.5],#Input Data [2.0, 5.0, -1.0, 2.0], [-1.5, 2.7, 3.3, -0.8]] class Layer_Dense: def __init__(self, n_inputs, n_neurons): self.weights = 0.10 * np.random.randn(n_inputs, n_neurons) self.biases = np.zeros((1, n_neurons)) def forward(self, inputs): self.output = np.dot(inputs, self.weights + self.biases) layer1 = Layer_Dense(4, 5) layer2 = Layer_Dense(5, 2) layer1.forward(X) print("Layer 1 Output") print(layer1.output) layer2.forward(layer1.output) print("Layer 2 Output") print(layer2.output)
[ "numpy.zeros", "numpy.dot", "numpy.random.seed", "numpy.random.randn" ]
[((61, 78), 'numpy.random.seed', 'np.random.seed', (['(0)'], {}), '(0)\n', (75, 78), True, 'import numpy as np\n'), ((329, 353), 'numpy.zeros', 'np.zeros', (['(1, n_neurons)'], {}), '((1, n_neurons))\n', (337, 353), True, 'import numpy as np\n'), ((409, 451), 'numpy.dot', 'np.dot', (['inputs', '(self.weights + self.biases)'], {}), '(inputs, self.weights + self.biases)\n', (415, 451), True, 'import numpy as np\n'), ((269, 305), 'numpy.random.randn', 'np.random.randn', (['n_inputs', 'n_neurons'], {}), '(n_inputs, n_neurons)\n', (284, 305), True, 'import numpy as np\n')]
import matplotlib as mpl import matplotlib.pyplot as plt import sympy as sp import numpy as np material = { 'red800' : '#C62828','red500' : '#F44336','red100' : '#FFCDD2','red50' : '#FFEBEE', 'orange800' : '#EF6C00','orange500' : '#FF9800','orange100' : '#FFCC80','orange50' : '#FFF3E0', 'yellow800' : '#F9A825','yellow500' : '#FFEB3B','yellow100' : '#FFF9C4','yellow50' : '#FFFDE7', 'green800' : '#2E7D32','green500' : '#4CAF50','green100' : '#C8E6C9','green50' : '#E8F5E9', 'blue800' : '#1565C0','blue500' : '#2196F3','blue100' : '#BBDEFB','blue50' : '#E3F2FD', 'deeppurple800' : '#4527A0','deeppurple500' : '#673AB7','deeppurple100' : '#D1C4E9','deeppurple50' : '#EDE7F6', 'gray800' : '#424242','gray500' : '#9E9E9E','gray100' : '#F5F5F5','gray50' : '#FAFAFA'} mpl.rcParams['text.usetex'] = True class MyStandardPlot(object): def resize(self): left, right = plt.xlim() bot, top = plt.ylim() height = (top - bot) / (right - left) * 4.0 self.fig.set_size_inches(4.0,height) def disk(self,x,y,r): c = plt.Circle((x,y),r) self.canvas.add_artist(c) def arrow(self,x,y,dx,dy): dl = dx if (dl < 0): dl = - dl if (dy > dl): dl = dy elif (-dy > dl): dl = -dy plt.arrow(x,y,dx,dy,head_length=0.07*dl,head_width=0.07*dl) def destroy(self): self.fig.clear() plt.close(self.fig) def __init__(self): self.fig = plt.figure() self.canvas = plt.axes() self.canvas.spines['top'].set_visible(False) self.canvas.spines['right'].set_visible(False) self.canvas.spines['left'].set_position('zero') self.canvas.spines['bottom'].set_position('zero') plt.gca().set_aspect('equal',adjustable='box') plt.tight_layout(4.0) self.fig.set_size_inches(4.0,4.0) def plot(self,list1,list2,colorno = 0): if (colorno == -1): colorname = '#000000' if (colorno == 0): colorname = material['deeppurple500'] if (colorno == 1): colorname = material['red500'] if (colorno == 2): colorname = material['orange500'] if (colorno == 3): colorname = material['yellow500'] if (colorno == 4): colorname = material['green500'] if (colorno == 5): colorname = material['blue500'] self.canvas.plot(list1,list2,color=colorname) def thinplot(self,list1,list2,lw,colorno = 0): if (colorno == -1): colorname = '#000000' if (colorno == 0): colorname = material['deeppurple500'] if (colorno == 1): colorname = material['red500'] self.canvas.plot(list1,list2,color=colorname,linewidth=lw) def fill(self,list1,list2,colorno = 0): if (colorno == 0): colorname = material['deeppurple100'] if (colorno == 1): colorname = material['red100'] self.canvas.fill(list1,list2,color=colorname) def xaxis(self,descriptor='center'): # can be bottom,zero,center,top if descriptor == 'bottom': self.canvas.spines['bottom'].set_position(('axes',0)) return elif descriptor == 'top': self.canvas.spines['bottom'].set_position(('axes',1)) return self.canvas.spines['bottom'].set_position(descriptor) def yaxis(self,descriptor='center'): # can be left,zero,center,top if descriptor == 'left': self.canvas.spines['left'].set_position(('axes',0)) return elif descriptor == 'right': self.canvas.spines['left'].set_position(('axes',1)) return self.canvas.spines['left'].set_position(descriptor) def xticks(self,ticklist): rawticks = [] ticknames = [] for item in ticklist: rawticks.append(float(item)) ticknames.append(r'$\displaystyle ' + sp.latex(item) + '$') plt.xticks(rawticks,ticknames) def yticks(self,ticklist): rawticks = [] ticknames = [] for item in ticklist: rawticks.append(float(item)) ticknames.append(r'$\displaystyle ' + sp.latex(item) + '$') plt.yticks(rawticks,ticknames) def text(self,x,y,s,horizontal='center',vertical='center'): self.canvas.text(x,y,s,fontsize=12,ha=horizontal,va=vertical) def mathlabel(self,x,y,s,horizontal='center',vertical='center'): totext = r'$\displaystyle ' + s + '$' self.canvas.text(x,y,totext,fontsize=12,ha=horizontal,va=vertical) def xlim(self,x0,x1): plt.xlim(float(x0),float(x1)) def ylim(self,y0,y1): plt.ylim(float(y0),float(y1)) def saveas(self,filename): self.fig.savefig(filename,format='png',dpi=320,bbox_inches='tight',pad_inches=0) def show(self): plt.show() def ygraph(self,func,xdata,samples=100,color=0): x = np.linspace(float(xdata[1]),float(xdata[2]),samples) y = [] for xval in x: try: y.append(float(func.subs(xdata[0],xval))) except: y.append(float(func)) self.plot(x,y,color) def xgraph(self,func,xdata,samples=100,color=0): x = np.linspace(float(xdata[1]),float(xdata[2]),samples) y = [] for xval in x: try: y.append(float(func.subs(xdata[0],xval))) except: y.append(float(func)) self.plot(y,x,color) def slopefield(self,func,xdata,ydata,samples=21,length=-1,color=0): x = np.linspace(float(xdata[1]),float(xdata[2]),samples) y = np.linspace(float(ydata[1]),float(ydata[2]),samples) if length <= 0: length = (float(xdata[2]) - float(xdata[1]))/float(samples+5) for xval in x: for yval in y: try: slope = float(func.subs(xdata[0],xval).subs(ydata[0],yval)) except: slope = float(func) dx = length / np.sqrt(1.0 + slope*slope) dy = dx * slope self.thinplot([xval - dx*0.5,xval+dx*0.5],[yval-0.5*dy,yval+0.5*dy],0.5,color) def yfillbetween(self,funcs,xdata,samples=100,color=0,closed=True,swap=False): x = np.linspace(float(xdata[1]),float(xdata[2]),samples) x1 = [] x2 = [] y1 = [] y2 = [] for xval in x: x1.append(xval) x2.append(xval) try: y1.append(float(funcs[0].subs(xdata[0],xval))) except: y1.append(float(funcs[0])) try: y2.append(float(funcs[1].subs(xdata[0],xval))) except: y2.append(float(funcs[1])) x2.reverse() y2.reverse() if swap: x3 = x1 x1 = y1 y1 = x3 x3 = x2 x2 = y2 y2 = x3 self.fill(x1+x2,y1+y2,color) if not closed: self.plot(x1,y1,color) self.plot(x2,y2,color) else: x2.append(x1[0]) y2.append(y1[0]) self.plot(x1+x2,y1+y2,color) def xfillbetween(self,funcs,xdata,samples=100,color=0,closed=True): return self.yfillbetween(funcs,xdata,samples,color,closed,swap=True) if __name__ == '__main__': x = sp.Symbol('x') myPlot = MyStandardPlot() #myPlot.xlim(-3.3,3.3) #myPlot.ylim(-3.3,3.3) myPlot.yfillbetween([sp.cos(x)-1,sp.cos(x)],(x,-sp.pi,sp.pi),closed=False) myPlot.xticks([-sp.pi,sp.pi]) myPlot.yticks([-1,1]) #myPlot.xaxis('center') #myPlot.yaxis('center') myPlot.math(1.0,0.5,r'y = \cos x') myPlot.show() #myPlot.saveas('test.svg')
[ "sympy.Symbol", "matplotlib.pyplot.xlim", "matplotlib.pyplot.show", "matplotlib.pyplot.ylim", "matplotlib.pyplot.axes", "matplotlib.pyplot.close", "matplotlib.pyplot.yticks", "sympy.cos", "sympy.latex", "matplotlib.pyplot.figure", "matplotlib.pyplot.Circle", "matplotlib.pyplot.xticks", "matp...
[((7444, 7458), 'sympy.Symbol', 'sp.Symbol', (['"""x"""'], {}), "('x')\n", (7453, 7458), True, 'import sympy as sp\n'), ((882, 892), 'matplotlib.pyplot.xlim', 'plt.xlim', ([], {}), '()\n', (890, 892), True, 'import matplotlib.pyplot as plt\n'), ((912, 922), 'matplotlib.pyplot.ylim', 'plt.ylim', ([], {}), '()\n', (920, 922), True, 'import matplotlib.pyplot as plt\n'), ((1058, 1079), 'matplotlib.pyplot.Circle', 'plt.Circle', (['(x, y)', 'r'], {}), '((x, y), r)\n', (1068, 1079), True, 'import matplotlib.pyplot as plt\n'), ((1298, 1366), 'matplotlib.pyplot.arrow', 'plt.arrow', (['x', 'y', 'dx', 'dy'], {'head_length': '(0.07 * dl)', 'head_width': '(0.07 * dl)'}), '(x, y, dx, dy, head_length=0.07 * dl, head_width=0.07 * dl)\n', (1307, 1366), True, 'import matplotlib.pyplot as plt\n'), ((1415, 1434), 'matplotlib.pyplot.close', 'plt.close', (['self.fig'], {}), '(self.fig)\n', (1424, 1434), True, 'import matplotlib.pyplot as plt\n'), ((1478, 1490), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (1488, 1490), True, 'import matplotlib.pyplot as plt\n'), ((1513, 1523), 'matplotlib.pyplot.axes', 'plt.axes', ([], {}), '()\n', (1521, 1523), True, 'import matplotlib.pyplot as plt\n'), ((1809, 1830), 'matplotlib.pyplot.tight_layout', 'plt.tight_layout', (['(4.0)'], {}), '(4.0)\n', (1825, 1830), True, 'import matplotlib.pyplot as plt\n'), ((4024, 4055), 'matplotlib.pyplot.xticks', 'plt.xticks', (['rawticks', 'ticknames'], {}), '(rawticks, ticknames)\n', (4034, 4055), True, 'import matplotlib.pyplot as plt\n'), ((4282, 4313), 'matplotlib.pyplot.yticks', 'plt.yticks', (['rawticks', 'ticknames'], {}), '(rawticks, ticknames)\n', (4292, 4313), True, 'import matplotlib.pyplot as plt\n'), ((4913, 4923), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (4921, 4923), True, 'import matplotlib.pyplot as plt\n'), ((7580, 7589), 'sympy.cos', 'sp.cos', (['x'], {}), '(x)\n', (7586, 7589), True, 'import sympy as sp\n'), ((1754, 1763), 'matplotlib.pyplot.gca', 'plt.gca', ([], {}), '()\n', (1761, 1763), True, 'import matplotlib.pyplot as plt\n'), ((7568, 7577), 'sympy.cos', 'sp.cos', (['x'], {}), '(x)\n', (7574, 7577), True, 'import sympy as sp\n'), ((6105, 6133), 'numpy.sqrt', 'np.sqrt', (['(1.0 + slope * slope)'], {}), '(1.0 + slope * slope)\n', (6112, 6133), True, 'import numpy as np\n'), ((3994, 4008), 'sympy.latex', 'sp.latex', (['item'], {}), '(item)\n', (4002, 4008), True, 'import sympy as sp\n'), ((4252, 4266), 'sympy.latex', 'sp.latex', (['item'], {}), '(item)\n', (4260, 4266), True, 'import sympy as sp\n')]
import sys import pandas as pd import numpy as np from sqlalchemy import create_engine import re import time import nltk nltk.download('words') nltk.download('punkt') nltk.download('averaged_perceptron_tagger') nltk.download('maxent_ne_chunker') nltk.download('stopwords') nltk.download('wordnet') from nltk.tokenize import word_tokenize from nltk.corpus import stopwords from nltk.stem.porter import PorterStemmer from nltk.stem.wordnet import WordNetLemmatizer from sklearn.pipeline import Pipeline from sklearn.feature_extraction.text import CountVectorizer from sklearn.feature_extraction.text import TfidfTransformer from sklearn.multioutput import MultiOutputClassifier from sklearn.ensemble import RandomForestClassifier, AdaBoostClassifier from sklearn.model_selection import train_test_split, GridSearchCV from sklearn.metrics import classification_report, f1_score, make_scorer import pickle from IPython.display import FileLink def load_data(database_filepath): """ Loading the data from the database created in the process_data.py program. Parameters: database_filepath: str Database location e.g '../folder_name/database_name.db' Returns: X: Dataframe Contains the message column Y: Dataframe Contains 36 output columns that have the message categorization category_names: list List of output column names of Y dataframe""" # load data from database engine = create_engine('sqlite:///'+database_filepath) #engine = create_engine('sqlite:///{}'.format(database_filename)) df = pd.read_sql_table('EmergencyMessage', engine, ) # Splitting the dataframe into X and Y X= df.message Y= df.iloc[:,4:] return X,Y, Y.columns def tokenize(text): """Function to tokenize the given text. It removes punctuation, lowers the case, removes the stopwords, lemmatizes and stems the words in the text. Parameters: text: str The input text that needs to be tokenized Returns: List that is tokenized """ # replace punctuations with spaces and change text to lower case temp = word_tokenize(re.sub(r'[\W]',' ',text).lower()) # remove stop words from the sentence words= [x for x in temp if x not in stopwords.words('english')] # lemmatize and stem the words return [PorterStemmer().stem( WordNetLemmatizer().lemmatize(w)) for w in words] def build_model(): """ Function that builds the pipeline to tokenize the text and develops the keywords into a matrix using CountVectorizer and TFIDF transformer\ It also uses RandomForest and Multioutput classifier to classify the message. Parameters: None Returns: cv: pipeline and GridSearch object""" # Creating the Pipeline pipeline = Pipeline([('vect', CountVectorizer(tokenizer= tokenize)), ('tfidf', TfidfTransformer()), ('clf', MultiOutputClassifier(RandomForestClassifier()))]) # Setting up a grid search with Random forest to find the best parameters parameters = {'clf__estimator__max_depth': [300], # [200,300, None] #'clf__estimator__min_samples_leaf': [1,4], #'clf__estimator__min_samples_split': [2,5], 'clf__estimator__n_estimators': [80], # [20,80 #'tfidf__use_idf':[True, False] } # Setting f1_score with micro averaging as the scorer for the gridsearch my_scorer = make_scorer(f1_score,average='micro' ) cv = GridSearchCV(estimator= pipeline, param_grid= parameters, scoring= my_scorer, cv=3, verbose= 2, n_jobs= 2 ) #Using Ada Boost Classifier algorithm for classification pipeline2 = Pipeline( [ ('vect', CountVectorizer(tokenizer= tokenize)), ('tfidf', TfidfTransformer()), ('clf', MultiOutputClassifier(AdaBoostClassifier() )) ]) # Setting different possible hyper-parameter values parameter2= {'clf__estimator__learning_rate': [1], # [0.1,1,10] 'clf__estimator__n_estimators': [100], # [80,100,150,200] } cv2 = GridSearchCV(estimator= pipeline2, param_grid= parameter2, scoring= my_scorer, cv=3, verbose= 2, n_jobs= 3) return cv2 def evaluate_model(model, X_test, y_test, category_names): """Function to find the F1 score for the test dataset using the trained model. It prints the necessary metrics (precision, recall and F1 score) for each ooutput column and\ also prints the aggregate F1 score for all the columns. Parameters: model: pipeline gridsearch object X_test: Dataframe Dataframe with test input values y_test: Dataframe Dataframe with test output labels category_names: list List of output columns of Y dataframe. Returns: None""" #Predicting the values of X_test y_test_pred= model.predict(X_test) # Iterating through the columns to generate F1 score for each column for i,col in enumerate(y_test.columns): print(col,'\n', classification_report(y_test[col], np.transpose(y_test_pred)[i])) print('F1 Score Aggregate \nTest :', f1_score(y_test,y_test_pred, average= 'micro') ) def save_model(model, model_filepath): """Saves the model provided into the desired location into a pickle format. Parameters: model: best GridSearch model model_filepath: str Path where the model has to be stored Returns: None""" pickle.dump(model, open(model_filepath,'wb')) FileLink(model_filepath) def main(): if len(sys.argv) == 3: database_filepath, model_filepath = sys.argv[1:] print('Loading data...\n DATABASE: {}'.format(database_filepath)) X, Y, category_names = load_data(database_filepath) X_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size=0.2) print('Building model...') model = build_model() print('Training model...') model.fit(X_train, Y_train) print('Evaluating model...') evaluate_model(model, X_test, Y_test, category_names) print('Saving model...\n MODEL: {}'.format(model_filepath)) save_model(model, model_filepath) print('Trained model saved!') else: print('Please provide the filepath of the disaster messages database '\ 'as the first argument and the filepath of the pickle file to '\ 'save the model to as the second argument. \n\nExample: python '\ 'train_classifier.py ../data/DisasterResponse.db classifier.pkl') if __name__ == '__main__': main()
[ "sklearn.ensemble.RandomForestClassifier", "sklearn.model_selection.GridSearchCV", "sklearn.feature_extraction.text.CountVectorizer", "sklearn.ensemble.AdaBoostClassifier", "nltk.stem.wordnet.WordNetLemmatizer", "sklearn.model_selection.train_test_split", "nltk.stem.porter.PorterStemmer", "numpy.trans...
[((121, 143), 'nltk.download', 'nltk.download', (['"""words"""'], {}), "('words')\n", (134, 143), False, 'import nltk\n'), ((144, 166), 'nltk.download', 'nltk.download', (['"""punkt"""'], {}), "('punkt')\n", (157, 166), False, 'import nltk\n'), ((167, 210), 'nltk.download', 'nltk.download', (['"""averaged_perceptron_tagger"""'], {}), "('averaged_perceptron_tagger')\n", (180, 210), False, 'import nltk\n'), ((211, 245), 'nltk.download', 'nltk.download', (['"""maxent_ne_chunker"""'], {}), "('maxent_ne_chunker')\n", (224, 245), False, 'import nltk\n'), ((246, 272), 'nltk.download', 'nltk.download', (['"""stopwords"""'], {}), "('stopwords')\n", (259, 272), False, 'import nltk\n'), ((273, 297), 'nltk.download', 'nltk.download', (['"""wordnet"""'], {}), "('wordnet')\n", (286, 297), False, 'import nltk\n'), ((1455, 1502), 'sqlalchemy.create_engine', 'create_engine', (["('sqlite:///' + database_filepath)"], {}), "('sqlite:///' + database_filepath)\n", (1468, 1502), False, 'from sqlalchemy import create_engine\n'), ((1580, 1625), 'pandas.read_sql_table', 'pd.read_sql_table', (['"""EmergencyMessage"""', 'engine'], {}), "('EmergencyMessage', engine)\n", (1597, 1625), True, 'import pandas as pd\n'), ((3489, 3527), 'sklearn.metrics.make_scorer', 'make_scorer', (['f1_score'], {'average': '"""micro"""'}), "(f1_score, average='micro')\n", (3500, 3527), False, 'from sklearn.metrics import classification_report, f1_score, make_scorer\n'), ((3538, 3643), 'sklearn.model_selection.GridSearchCV', 'GridSearchCV', ([], {'estimator': 'pipeline', 'param_grid': 'parameters', 'scoring': 'my_scorer', 'cv': '(3)', 'verbose': '(2)', 'n_jobs': '(2)'}), '(estimator=pipeline, param_grid=parameters, scoring=my_scorer,\n cv=3, verbose=2, n_jobs=2)\n', (3550, 3643), False, 'from sklearn.model_selection import train_test_split, GridSearchCV\n'), ((4104, 4210), 'sklearn.model_selection.GridSearchCV', 'GridSearchCV', ([], {'estimator': 'pipeline2', 'param_grid': 'parameter2', 'scoring': 'my_scorer', 'cv': '(3)', 'verbose': '(2)', 'n_jobs': '(3)'}), '(estimator=pipeline2, param_grid=parameter2, scoring=my_scorer,\n cv=3, verbose=2, n_jobs=3)\n', (4116, 4210), False, 'from sklearn.model_selection import train_test_split, GridSearchCV\n'), ((5600, 5624), 'IPython.display.FileLink', 'FileLink', (['model_filepath'], {}), '(model_filepath)\n', (5608, 5624), False, 'from IPython.display import FileLink\n'), ((5206, 5252), 'sklearn.metrics.f1_score', 'f1_score', (['y_test', 'y_test_pred'], {'average': '"""micro"""'}), "(y_test, y_test_pred, average='micro')\n", (5214, 5252), False, 'from sklearn.metrics import classification_report, f1_score, make_scorer\n'), ((5903, 5940), 'sklearn.model_selection.train_test_split', 'train_test_split', (['X', 'Y'], {'test_size': '(0.2)'}), '(X, Y, test_size=0.2)\n', (5919, 5940), False, 'from sklearn.model_selection import train_test_split, GridSearchCV\n'), ((2153, 2179), 're.sub', 're.sub', (['"""[\\\\W]"""', '""" """', 'text'], {}), "('[\\\\W]', ' ', text)\n", (2159, 2179), False, 'import re\n'), ((2274, 2300), 'nltk.corpus.stopwords.words', 'stopwords.words', (['"""english"""'], {}), "('english')\n", (2289, 2300), False, 'from nltk.corpus import stopwords\n'), ((2354, 2369), 'nltk.stem.porter.PorterStemmer', 'PorterStemmer', ([], {}), '()\n', (2367, 2369), False, 'from nltk.stem.porter import PorterStemmer\n'), ((2834, 2869), 'sklearn.feature_extraction.text.CountVectorizer', 'CountVectorizer', ([], {'tokenizer': 'tokenize'}), '(tokenizer=tokenize)\n', (2849, 2869), False, 'from sklearn.feature_extraction.text import CountVectorizer\n'), ((2891, 2909), 'sklearn.feature_extraction.text.TfidfTransformer', 'TfidfTransformer', ([], {}), '()\n', (2907, 2909), False, 'from sklearn.feature_extraction.text import TfidfTransformer\n'), ((3753, 3788), 'sklearn.feature_extraction.text.CountVectorizer', 'CountVectorizer', ([], {'tokenizer': 'tokenize'}), '(tokenizer=tokenize)\n', (3768, 3788), False, 'from sklearn.feature_extraction.text import CountVectorizer\n'), ((3810, 3828), 'sklearn.feature_extraction.text.TfidfTransformer', 'TfidfTransformer', ([], {}), '()\n', (3826, 3828), False, 'from sklearn.feature_extraction.text import TfidfTransformer\n'), ((2376, 2395), 'nltk.stem.wordnet.WordNetLemmatizer', 'WordNetLemmatizer', ([], {}), '()\n', (2393, 2395), False, 'from nltk.stem.wordnet import WordNetLemmatizer\n'), ((2950, 2974), 'sklearn.ensemble.RandomForestClassifier', 'RandomForestClassifier', ([], {}), '()\n', (2972, 2974), False, 'from sklearn.ensemble import RandomForestClassifier, AdaBoostClassifier\n'), ((3869, 3889), 'sklearn.ensemble.AdaBoostClassifier', 'AdaBoostClassifier', ([], {}), '()\n', (3887, 3889), False, 'from sklearn.ensemble import RandomForestClassifier, AdaBoostClassifier\n'), ((5124, 5149), 'numpy.transpose', 'np.transpose', (['y_test_pred'], {}), '(y_test_pred)\n', (5136, 5149), True, 'import numpy as np\n')]
import dgl import torch import torch.nn as nn import torch.nn.functional as F import dgl.data import numpy as np import pandas as pd from make_dgl_dataset import PmuDataset import warnings from dgl.nn import GraphConv import matplotlib.pyplot as plt warnings.filterwarnings('ignore') # device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') # print('Using device:', device) features = np.load('data/features.npy') # labels = np.load('data/labels.npy') data = np.load('data/all_event_data.npy') # per_unit = np.load('data/all_per_unit.npy') per_unit = np.load('data/aug_all_per_unit_806_824_836_846.npy') labels = np.load('data/aug_labels_806_824_836_846.npy') dataset = PmuDataset() from dgl.dataloading import GraphDataLoader from torch.utils.data.sampler import SubsetRandomSampler num_examples = len(dataset) num_train = int(num_examples * 0.8) # num_examples = len(dataset) # num_train = int(num_examples * 0.9) # # train_sampler = SubsetRandomSampler(torch.arange(num_train)) # test_sampler = SubsetRandomSampler(torch.arange(num_train, num_examples)) train_selector = np.random.choice(num_examples, num_train, replace=False) test_selector = np.setdiff1d(np.arange(num_examples), train_selector) train_sampler = SubsetRandomSampler(torch.from_numpy(train_selector)) test_sampler = SubsetRandomSampler(torch.from_numpy(test_selector)) #%% b_size = 100 train_dataloader = GraphDataLoader( dataset, sampler=train_sampler, batch_size=b_size, drop_last=False) test_dataloader = GraphDataLoader( dataset, sampler=test_sampler, batch_size=b_size, drop_last=False) class GCN(nn.Module): def __init__(self, in_feats, h1_feats, h2_feats, num_classes): super(GCN, self).__init__() self.conv1 = GraphConv(in_feats, h1_feats) self.conv2 = GraphConv(h1_feats, h2_feats) self.conv3 = GraphConv(h2_feats, num_classes) def forward(self, g, in_feat): h = self.conv1(g, in_feat) h = F.leaky_relu(h) h = self.conv2(g, h) h = F.leaky_relu(h) h = self.conv3(g, h) g.ndata['h'] = h return dgl.mean_nodes(g, 'h') # Create the model with given dimensions #%% model = GCN(9*125, 512, 256, np.unique(labels).shape[0]) # model.to(device) optimizer = torch.optim.Adam(model.parameters(), lr=0.01) epoch_number = 20 for epoch in range(epoch_number): acc = 0 rnd = 0 for batched_graph, tags in train_dataloader: num_correct = 0 num_trains = 0 pred = model(batched_graph, batched_graph.ndata['features'].float()) loss = F.cross_entropy(pred, tags) optimizer.zero_grad() loss.backward() optimizer.step() num_correct += (pred.argmax(1) == tags).sum().item() # print(pred.argmax(1), labels) num_trains += len(tags) acc += num_correct / num_trains rnd += 1 print(epoch, acc/rnd) # print('Test accuracy:', num_correct / num_trains) # print(pred.argmax(1), labels) # print(epoch) from sklearn import metrics num_correct = 0 num_tests = 0 y_pred = np.array([]) y_real = np.array([]) for batched_graph, tags in test_dataloader: pred = model(batched_graph, batched_graph.ndata['features'].float()) num_correct += (pred.argmax(1) == tags).sum().item() # print(pred.argmax(1), tags) pred = pred.detach().numpy() tags = tags.detach().numpy() # print(pred.argmax(1)) num_tests += len(tags) y_pred = np.append(y_pred, pred.argmax(1).ravel()) y_real = np.append(y_real, tags.ravel()) # y_pred = np.ravel(y_pred) # y_real = np.ravel(y_real) print('test accuracy (ARS)', metrics.adjusted_rand_score(y_real, y_pred)) for batched_graph, tags in train_dataloader: pred = model(batched_graph, batched_graph.ndata['features'].float()) num_correct += (pred.argmax(1) == tags).sum().item() # print(pred.argmax(1), tags) pred = pred.detach().numpy() tags = tags.detach().numpy() # print(pred.argmax(1)) num_tests += len(tags) y_pred = np.append(y_pred, pred.argmax(1).ravel()) y_real = np.append(y_real, tags.ravel()) # y_pred = np.ravel(y_pred) # y_real = np.ravel(y_real) print('trian accuracy (ARS)', metrics.adjusted_rand_score(y_real, y_pred)) #%% num_correct = 0 num_tests = 0 for batched_graph, tags in test_dataloader: pred = model(batched_graph, batched_graph.ndata['features'].float()) num_correct += (pred.argmax(1) == tags).sum().item() # print(pred.argmax(1), tags) num_tests += len(tags) print('Test accuracy:', num_correct / num_tests) #%% from sklearn import metrics num_correct = 0 num_tests = 0 y_pred = np.array([]) y_real = np.array([]) for batched_graph, tags in test_dataloader: pred = model(batched_graph, batched_graph.ndata['features'].float()) num_correct += (pred.argmax(1) == tags).sum().item() # print(pred.argmax(1), tags) pred = pred.detach().numpy() tags = tags.detach().numpy() print(pred.argmax(1)) num_tests += len(tags) y_pred = np.append(y_pred, pred.argmax(1).ravel()) y_real = np.append(y_real, tags.ravel()) # y_pred = np.ravel(y_pred) # y_real = np.ravel(y_real) print(metrics.adjusted_rand_score(y_real, y_pred)) print('Test accuracy:', num_correct / num_tests) #%% import networkx as nx import dgl g_nx = nx.petersen_graph() g_dgl = dgl.DGLGraph(g_nx) import matplotlib.pyplot as plt # plt.subplot(121) # nx.draw(g_nx, with_labels=True) plt.subplot(111) nx.draw(dataset[0][0].to_networkx(), with_labels=True) plt.show()
[ "matplotlib.pyplot.subplot", "numpy.load", "dgl.dataloading.GraphDataLoader", "matplotlib.pyplot.show", "warnings.filterwarnings", "networkx.petersen_graph", "torch.nn.functional.cross_entropy", "make_dgl_dataset.PmuDataset", "dgl.DGLGraph", "numpy.array", "numpy.arange", "torch.nn.functional....
[((263, 296), 'warnings.filterwarnings', 'warnings.filterwarnings', (['"""ignore"""'], {}), "('ignore')\n", (286, 296), False, 'import warnings\n'), ((418, 446), 'numpy.load', 'np.load', (['"""data/features.npy"""'], {}), "('data/features.npy')\n", (425, 446), True, 'import numpy as np\n'), ((494, 528), 'numpy.load', 'np.load', (['"""data/all_event_data.npy"""'], {}), "('data/all_event_data.npy')\n", (501, 528), True, 'import numpy as np\n'), ((588, 640), 'numpy.load', 'np.load', (['"""data/aug_all_per_unit_806_824_836_846.npy"""'], {}), "('data/aug_all_per_unit_806_824_836_846.npy')\n", (595, 640), True, 'import numpy as np\n'), ((651, 697), 'numpy.load', 'np.load', (['"""data/aug_labels_806_824_836_846.npy"""'], {}), "('data/aug_labels_806_824_836_846.npy')\n", (658, 697), True, 'import numpy as np\n'), ((713, 725), 'make_dgl_dataset.PmuDataset', 'PmuDataset', ([], {}), '()\n', (723, 725), False, 'from make_dgl_dataset import PmuDataset\n'), ((1135, 1191), 'numpy.random.choice', 'np.random.choice', (['num_examples', 'num_train'], {'replace': '(False)'}), '(num_examples, num_train, replace=False)\n', (1151, 1191), True, 'import numpy as np\n'), ((1450, 1537), 'dgl.dataloading.GraphDataLoader', 'GraphDataLoader', (['dataset'], {'sampler': 'train_sampler', 'batch_size': 'b_size', 'drop_last': '(False)'}), '(dataset, sampler=train_sampler, batch_size=b_size,\n drop_last=False)\n', (1465, 1537), False, 'from dgl.dataloading import GraphDataLoader\n'), ((1559, 1646), 'dgl.dataloading.GraphDataLoader', 'GraphDataLoader', (['dataset'], {'sampler': 'test_sampler', 'batch_size': 'b_size', 'drop_last': '(False)'}), '(dataset, sampler=test_sampler, batch_size=b_size, drop_last\n =False)\n', (1574, 1646), False, 'from dgl.dataloading import GraphDataLoader\n'), ((3186, 3198), 'numpy.array', 'np.array', (['[]'], {}), '([])\n', (3194, 3198), True, 'import numpy as np\n'), ((3209, 3221), 'numpy.array', 'np.array', (['[]'], {}), '([])\n', (3217, 3221), True, 'import numpy as np\n'), ((4785, 4797), 'numpy.array', 'np.array', (['[]'], {}), '([])\n', (4793, 4797), True, 'import numpy as np\n'), ((4808, 4820), 'numpy.array', 'np.array', (['[]'], {}), '([])\n', (4816, 4820), True, 'import numpy as np\n'), ((5478, 5497), 'networkx.petersen_graph', 'nx.petersen_graph', ([], {}), '()\n', (5495, 5497), True, 'import networkx as nx\n'), ((5507, 5525), 'dgl.DGLGraph', 'dgl.DGLGraph', (['g_nx'], {}), '(g_nx)\n', (5519, 5525), False, 'import dgl\n'), ((5617, 5633), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(111)'], {}), '(111)\n', (5628, 5633), True, 'import matplotlib.pyplot as plt\n'), ((5693, 5703), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (5701, 5703), True, 'import matplotlib.pyplot as plt\n'), ((1222, 1245), 'numpy.arange', 'np.arange', (['num_examples'], {}), '(num_examples)\n', (1231, 1245), True, 'import numpy as np\n'), ((1304, 1336), 'torch.from_numpy', 'torch.from_numpy', (['train_selector'], {}), '(train_selector)\n', (1320, 1336), False, 'import torch\n'), ((1374, 1405), 'torch.from_numpy', 'torch.from_numpy', (['test_selector'], {}), '(test_selector)\n', (1390, 1405), False, 'import torch\n'), ((3753, 3796), 'sklearn.metrics.adjusted_rand_score', 'metrics.adjusted_rand_score', (['y_real', 'y_pred'], {}), '(y_real, y_pred)\n', (3780, 3796), False, 'from sklearn import metrics\n'), ((4333, 4376), 'sklearn.metrics.adjusted_rand_score', 'metrics.adjusted_rand_score', (['y_real', 'y_pred'], {}), '(y_real, y_pred)\n', (4360, 4376), False, 'from sklearn import metrics\n'), ((5327, 5370), 'sklearn.metrics.adjusted_rand_score', 'metrics.adjusted_rand_score', (['y_real', 'y_pred'], {}), '(y_real, y_pred)\n', (5354, 5370), False, 'from sklearn import metrics\n'), ((1802, 1831), 'dgl.nn.GraphConv', 'GraphConv', (['in_feats', 'h1_feats'], {}), '(in_feats, h1_feats)\n', (1811, 1831), False, 'from dgl.nn import GraphConv\n'), ((1854, 1883), 'dgl.nn.GraphConv', 'GraphConv', (['h1_feats', 'h2_feats'], {}), '(h1_feats, h2_feats)\n', (1863, 1883), False, 'from dgl.nn import GraphConv\n'), ((1906, 1938), 'dgl.nn.GraphConv', 'GraphConv', (['h2_feats', 'num_classes'], {}), '(h2_feats, num_classes)\n', (1915, 1938), False, 'from dgl.nn import GraphConv\n'), ((2026, 2041), 'torch.nn.functional.leaky_relu', 'F.leaky_relu', (['h'], {}), '(h)\n', (2038, 2041), True, 'import torch.nn.functional as F\n'), ((2085, 2100), 'torch.nn.functional.leaky_relu', 'F.leaky_relu', (['h'], {}), '(h)\n', (2097, 2100), True, 'import torch.nn.functional as F\n'), ((2173, 2195), 'dgl.mean_nodes', 'dgl.mean_nodes', (['g', '"""h"""'], {}), "(g, 'h')\n", (2187, 2195), False, 'import dgl\n'), ((2659, 2686), 'torch.nn.functional.cross_entropy', 'F.cross_entropy', (['pred', 'tags'], {}), '(pred, tags)\n', (2674, 2686), True, 'import torch.nn.functional as F\n'), ((2277, 2294), 'numpy.unique', 'np.unique', (['labels'], {}), '(labels)\n', (2286, 2294), True, 'import numpy as np\n')]
"""Utility functions shared across the Aquarius project.""" import ftplib import os import logging import gzip import numpy as np import pandas as pd import yaml import json from datetime import timedelta, date, datetime from dfply import ( X, group_by, summarize, mask, n, transmute, select, left_join, ungroup, arrange, mutate, ) from tqdm import tqdm from typing import Tuple, Dict, List, Optional, NamedTuple from geopy.distance import geodesic from sqlalchemy import create_engine import matplotlib.pyplot as plt from bokeh.plotting import figure from bokeh.models import HoverTool, ColumnDataSource, VArea, Line, VBar from bokeh.tile_providers import get_provider, STAMEN_TERRAIN class ECDF: """Empirical Cumulative Distribution Function with linear interpolation.""" def __init__(self): self.x_values = None self.cdf_values = None def fit(self, xdata: np.ndarray, weights: Optional[np.ndarray] = None): if weights is None: ind_valid = ~np.isnan(xdata) xv = xdata[ind_valid] values, counts = np.unique(xv, return_counts=True) sort_index = np.argsort(values) self.x_values = values[sort_index] self.cdf_values = (np.cumsum(counts[sort_index]) - 0.5)/np.sum(counts) else: assert len(xdata) == len(weights) ind_valid = ~np.isnan(xdata) & ~np.isnan(weights) xv = xdata[ind_valid] wv = weights[ind_valid] sorter = np.argsort(xv) values = xv[sorter] sample_weight = wv[sorter] weighted_quantiles = (np.cumsum(sample_weight) - 0.5 * sample_weight) / np.sum(sample_weight) unique_values, unique_index, unique_counts = np.unique(values, return_index=True, return_counts=True) self.x_values = unique_values self.cdf_values = weighted_quantiles[unique_index + unique_counts - 1] # last index instead of first index return self def eval(self, x: np.ndarray): cdf = np.interp(x, xp=self.x_values, fp=self.cdf_values, left=0, right=1) return cdf def quantile(self, q: np.ndarray): assert np.all(q >= 0) and np.all(q <= 1), 'quantiles should be in [0, 1]' xq = np.interp(q, xp=self.cdf_values, fp=self.x_values, left=self.x_values[0], right=self.x_values[-1]) return xq def download_ghcn_file(ftp_filename: str, save_dir: str): logging.debug(f"ftp_filename={ftp_filename}") logging.debug(f"save_dir={save_dir}") ftp = ftplib.FTP(host='ftp.ncdc.noaa.gov', timeout=10.0, user='anonymous', passwd='<PASSWORD>') logging.debug("FTP server connected") ftp.cwd("/pub/data/ghcn/daily/by_year/") save_path = os.path.join(save_dir, ftp_filename) logging.debug(f"downloading {save_path}") with open(save_path, 'wb') as file: ftp.retrbinary(f"RETR {ftp_filename}", file.write) logging.debug(f"downloaded {save_path}") return 1 def unzip_file(filename: str, folder: str): read_path = os.path.join(folder, filename) logging.debug(f"unzipping {read_path}") f = gzip.open(read_path, 'rb') file_content = f.read() f.close() logging.debug(f"unzipped {read_path}") return file_content def df_file(filename: str, folder: str) -> pd.DataFrame: # based on https://stackoverflow.com/questions/31028815/how-to-unzip-gz-file-using-python read_path = os.path.join(folder, filename) logging.debug(f"unzipping and reading {read_path}") with gzip.open(read_path, 'rb') as f: df = pd.read_csv( f, header=None, names=['station', 'dateto', 'element', 'value', 'm_flag', 'q_flag', 's_flag', 'obs_time'], parse_dates=['dateto'], ) logging.debug(f"read {read_path}") return df def get_config(): with open('config.yaml', 'r') as file: config = yaml.safe_load(file) return config def load_all_years(year_from: int, year_to: int, save_dir: str): for year in range(year_from, year_to + 1): filename = f"{year}.csv.gz" download_ghcn_file(filename, save_dir) logging.debug("completed") def extract_one_prcp(filename: str, by_year_path: str, prcp_path: str): df = df_file(filename, by_year_path) df_sel = df >> mask(X.element == 'PRCP') >> transmute(station=X.station, dateto=X.dateto, prcp=X.value) logging.debug(f"{df_sel.shape[0]} out of {df.shape[0]} rows selected") year_string = filename.split('.')[0] df_sel.to_csv(os.path.join(prcp_path, f"{year_string}.csv"), sep=',', index=False) logging.debug(f"{filename} processed") def extract_one_station_prcp(station: str, filename: str, by_year_path: str, prcp_path: str): df = df_file(filename, by_year_path) df_sel = df >> mask(X.element == 'PRCP') >> mask(X.station == station) >> \ transmute(station=X.station, dateto=X.dateto, prcp=X.value) logging.debug(f"{df_sel.shape[0]} out of {df.shape[0]} rows selected") year_string = filename.split('.')[0] df_sel.to_csv(os.path.join(prcp_path, f"{year_string}.csv"), sep=',', index=False) logging.debug(f"{filename} processed") def extract_one_station_startswith(station_startswith: str, filename: str, by_year_path: str, prcp_path: str): df = df_file(filename, by_year_path) df_sel = df >> mask(X.element == 'PRCP') >> mask(X.station.str.startswith(station_startswith)) >> \ transmute(station=X.station, dateto=X.dateto, prcp=X.value) logging.debug(f"{df_sel.shape[0]} out of {df.shape[0]} rows selected") year_string = filename.split('.')[0] df_sel.to_csv(os.path.join(prcp_path, f"{year_string}.csv"), sep=',', index=False) logging.debug(f"{filename} processed") def extract_all_prcp(by_year_path: str, prcp_path: str): if not os.path.isdir(prcp_path): os.makedirs(prcp_path) for filename in sorted(os.listdir(by_year_path), reverse=True): extract_one_prcp(filename, by_year_path, prcp_path) return 1 def extract_all_prcp_station(station: str, by_year_path: str, prcp_path: str): if not os.path.isdir(prcp_path): os.makedirs(prcp_path) for filename in sorted(os.listdir(by_year_path), reverse=True): extract_one_station_prcp(station, filename, by_year_path, prcp_path) return 1 def extract_all_prcp_station_startswith(station_startswith: str, by_year_path: str, prcp_path: str): if not os.path.isdir(prcp_path): os.makedirs(prcp_path) for filename in sorted(os.listdir(by_year_path), reverse=True): extract_one_station_startswith(station_startswith, filename, by_year_path, prcp_path) return 1 def ded(prcp: pd.DataFrame) -> date: logging.debug(f"{prcp.shape[0]} station*days") station_ded = prcp >> group_by(X.station) >> summarize(ded=X.dateto.max()) logging.debug(f"{station_ded.shape[0]} stations") data_end_dt = station_ded['ded'].quantile(0.90) data_end_date = date(data_end_dt.year, data_end_dt.month, data_end_dt.day) logging.debug(f"data_end_date={data_end_date}") return data_end_date def date_limits(prcp: pd.DataFrame) -> tuple: logging.debug(f"{prcp.shape[0]} station*days") station_ded = prcp >> group_by(X.station) >> summarize(dsd=X.dateto.min(), ded=X.dateto.max()) logging.debug(f"{station_ded.shape[0]} stations") data_start_date = station_ded['dsd'].quantile(0.10) data_end_date = station_ded['ded'].quantile(0.90) return data_start_date, data_end_date def df_prcp(year: int, prcp_path=None) -> pd.DataFrame: if prcp_path is None: prcp_path = '../../data/prcp_ruzyne' filename = os.path.join(prcp_path, f'{year}.csv') logging.debug(f"reading {filename}") prcp = pd.read_csv(filename, parse_dates=['dateto']) >> arrange(X.dateto, X.station) return prcp def active_stations(prcp: pd.DataFrame, date_valid, config) -> pd.DataFrame: prcp_valid = prcp >> mask(X.dateto <= date_valid) data_end_date = ded(prcp_valid) logging.debug(f"data_end_date={data_end_date}") logging.debug(f"active_period_length_days={config['active_period_length_days']}") active_start_date = data_end_date - timedelta(days=config['active_period_length_days']-1) logging.debug(f"active_start_date={active_start_date}") prcp_window = prcp_valid >> mask(X.dateto >= active_start_date) prcp_active = prcp_window >> group_by(X.station) >> summarize(num_observed_days=n(X.prcp)) >> arrange(X.station) prcp_active['is_active'] = prcp_active['num_observed_days'] >= config['active_period_min_days'] return prcp_active >> ungroup() def transpose_to_stations(prcp_path: str, stations_path: str): # deprecated - too slow all_files = sorted(os.listdir(prcp_path), reverse=True) num_files = len(all_files) logging.debug(f"{num_files} files in {prcp_path}") for i_file, filename in enumerate(all_files): year = int(filename.split('.')[0]) df = df_prcp(year) stations = df['station'].unique().sort_values() num_stations = len(stations) logging.debug(f"{num_stations} stations in {filename}") for i_station, station in enumerate(stations): df_sel = df >> mask(X.station == station) >> select(X.dateto, X.prcp) out_filename = os.path.join(stations_path, f"{station}.csv") if os.path.isfile(out_filename): df_sel.to_csv(out_filename, mode='a', index=False, header=False) else: df_sel.to_csv(out_filename, mode='w', index=False, header=True) logging.debug(f"file={i_file}/{num_files} station={i_station}/{num_stations} processed") logging.debug(f"{filename} processed") logging.debug("transpose completed") def make_recent(data_end_date: date, config) -> pd.Series: """Make daily calendar with period taking values True=recent and False=preceding.""" num_days_recent = 365*config['recent_time_window_years'] num_days_preceding = 365*config['preceding_time_window_max_years'] num_days = num_days_recent + num_days_preceding date_axis = np.flip(pd.date_range(end=data_end_date, periods=num_days, freq='D')) calendar_values = np.concatenate([ np.ones(num_days_recent, dtype=bool), np.zeros(num_days_preceding, dtype=bool), ]) calendar = pd.Series(calendar_values, index=date_axis) logging.debug(( f"calendar with {num_days} days from {date_axis[-1]} to {date_axis[0]} " f"with recent period of {num_days_recent} from {date_axis[num_days_recent-1]}" )) return calendar def update_drought(df_running: pd.DataFrame, df_update: pd.DataFrame, calendar: pd.Series) -> pd.DataFrame: """Update drought statistics with time series from a new time period.""" if df_update.shape[0] > 0: assert "station" in df_running.columns assert "station" in df_update.columns assert "dateto" in df_update.columns running_columns = [ 'recent_time_window_days', 'recent_days_observed', 'recent_fill_rate', 'recent_precipitation_mm', 'recent_precipitation_annual_mean', 'preceding_time_window_days', 'preceding_days_observed', 'preceding_fill_rate', 'preceding_precipitation_mm', 'preceding_precipitation_annual_mean', ] for column in running_columns: if column not in df_running.columns: df_running[column] = 0 d1, d2 = date_limits(df_update) logging.debug(f"date_limits: {d1} and {d2}") calendar_recent = pd.DataFrame({'dateto': calendar[calendar].index}) recent_start_date = calendar_recent.iat[-1, 0] recent_end_date = calendar_recent.iat[0, 0] calendar_preceding = pd.DataFrame({'dateto': calendar[~calendar].index}) preceding_start_date = calendar_preceding.iat[-1, 0] preceding_end_date = calendar_preceding.iat[0, 0] d1_recent = max(d1, recent_start_date) d2_recent = min(d2, recent_end_date) recent_delta_days = max((d2_recent - d1_recent).days + 1, 0) logging.debug(f"recent_delta_days={recent_delta_days}") d1_preceding = max(d1, preceding_start_date) d2_preceding = min(d2, preceding_end_date) preceding_delta_days = max((d2_preceding - d1_preceding).days + 1, 0) logging.debug(f"preceding_delta_days={preceding_delta_days}") if (recent_delta_days > 0) or (preceding_delta_days > 0): logging.debug("proceeding") df_base = df_running[['station']].copy() df_update_recent = calendar_recent >> \ left_join(df_update, by='dateto') >> \ group_by(X.station) >> \ summarize( recent_days_observed=n(X.prcp), recent_precipitation_mm=X.prcp.sum()/10, ) if df_update_recent.shape[0] == 0: # df_update does not intersect recent window df_update_recent = df_base.copy() df_update_recent['recent_days_observed'] = 0 df_update_recent['recent_precipitation_mm'] = 0.0 # logging.debug(df_update_recent.head()) df_update_preceding = calendar_preceding >> \ left_join(df_update, by='dateto') >> \ group_by(X.station) >> \ summarize( preceding_days_observed=n(X.prcp), preceding_precipitation_mm=X.prcp.sum()/10 ) if df_update_preceding.shape[0] == 0: # df_update does not intersect preceding window df_update_preceding = df_base.copy() df_update_preceding['preceding_days_observed'] = 0 df_update_preceding['preceding_precipitation_mm'] = 0.0 # logging.debug(df_update_preceding.head()) df_delta = df_base.copy() >> \ left_join(df_update_recent, by='station') >> \ left_join(df_update_preceding, by='station') df_delta.fillna(value=0, inplace=True) assert df_delta.shape[0] == df_running.shape[0] recent_time_window_days = df_running.recent_time_window_days + recent_delta_days preceding_time_window_days = df_running.preceding_time_window_days + preceding_delta_days recent_days_observed = df_running.recent_days_observed + df_delta.recent_days_observed preceding_days_observed = df_running.preceding_days_observed + df_delta.preceding_days_observed recent_fill_rate = recent_days_observed / recent_time_window_days preceding_fill_rate = preceding_days_observed / preceding_time_window_days recent_precipitation_mm = df_running.ecent_precipitation_mm + df_delta.recent_precipitation_mm preceding_precipitation_mm = df_running.preceding_precipitation_mm + df_delta.preceding_precipitation_mm recent_precipitation_annual_mean = recent_precipitation_mm / recent_days_observed * 365 preceding_prcp_annual_mean = preceding_precipitation_mm / preceding_days_observed * 365 df_running['recent_time_window_days'] = recent_time_window_days df_running['recent_days_observed'] = recent_days_observed df_running['recent_fill_rate'] = recent_fill_rate df_running['recent_precipitation_mm'] = recent_precipitation_mm df_running['recent_precipitation_annual_mean'] = recent_precipitation_annual_mean df_running['preceding_time_window_days'] = preceding_time_window_days df_running['preceding_days_observed'] = preceding_days_observed df_running['preceding_fill_rate'] = preceding_fill_rate df_running['preceding_precipitation_mm'] = preceding_precipitation_mm df_running['preceding_precipitation_annual_mean'] = preceding_prcp_annual_mean df_running['dq_flag'] = (recent_fill_rate >= 0.90) & (preceding_fill_rate >= 0.80) df_running['drought_index'] = 100*(1 - recent_precipitation_annual_mean / preceding_prcp_annual_mean) else: logging.debug("skipping") else: logging.debug("df_running is empty") return df_running def get_current_year() -> int: y0 = date.today().year return y0 def get_oldest_year() -> int: current_year = get_current_year() config = get_config() oldest_year = current_year - \ config['drought_window_years'] - \ config['recent_time_window_years'] - \ config['preceding_time_window_min_years'] return oldest_year def calculate_drought( stations: pd.DataFrame, data_end_date: date, prcp_path: str, out_path: str, ) -> pd.DataFrame: logging.info(f"{stations.shape[0]} active stations with data_end_date={data_end_date}") config = get_config() calendar = make_recent(data_end_date, config) year_to = calendar.index[0].year year_from = calendar.index[-1].year years = range(year_to, year_from - 1, -1) logging.info(f"processing {len(years)} years from {year_to} back to {year_from}") for year in years: logging.info(f"year={year}") prcp_year = df_prcp(year, prcp_path) stations = update_drought(stations, prcp_year, calendar) logging.info(f"{stations['dq_flag'].sum()} data quality passed") stations.to_csv(f'{out_path}/{data_end_date.isoformat()[:10]}.csv', index=False) logging.debug(f"\n{stations.head(10)}") aquarius = stations >> mask(X.dq_flag) >> \ summarize( min=X.drought_index.min(), p25=X.drought_index.quantile(0.25), p50=X.drought_index.quantile(0.50), p75=X.drought_index.quantile(0.75), max=X.drought_index.max(), ) return aquarius def load_countries() -> pd.DataFrame: countries_file = '../../data/station/ghcnd-countries-continent.txt' cdf_list = [] with open(countries_file, 'r') as file: for line in file: country_code = line[:2] continent_code = line[3:5] country_name = line[6:].rstrip() cdf_row = (country_code, continent_code, country_name) cdf_list.append(cdf_row) logging.debug(f"{len(cdf_list)} countries parsed") cdf = pd.DataFrame(cdf_list, columns=['country_code', 'continent_code', 'country_name']) continent = { 'EU': 'Europe', 'AS': 'Asia', 'AF': 'Africa', 'NA': 'North America', 'SA': 'South America', 'OC': 'Oceania', 'AN': 'Antarctica', } cdf['continent_name'] = cdf['continent_code'].apply(lambda x: continent[x]) return cdf def load_stations() -> pd.DataFrame: stations_file = '../../data/station/ghcnd-stations.txt' stations_list = [] with open(stations_file, 'r') as file: for line in file: country_code = line[:2] station = line[:11] latitude = float(line[12:20]) longitude = float(line[21:30]) elevation = float(line[31:37]) station_name = line[41:71].rstrip().lower() stations_row = (station, country_code, latitude, longitude, elevation, station_name) stations_list.append(stations_row) logging.debug(f"{len(stations_list)} stations parsed") colnames = ['station', 'country_code', 'latitude', 'longitude', 'elevation', 'station_name'] sdfbase = pd.DataFrame(stations_list, columns=colnames) cdf = load_countries() sdf = sdfbase.merge(cdf, how='left', on='country_code').set_index('station') return sdf def load_country_continent() -> pd.DataFrame: cc_file = '../../data/station/country-and-continent-codes-list-csv_csv.txt' ccdf = pd.read_csv(cc_file, sep=",") return ccdf def chunker(seq, size): # from http://stackoverflow.com/a/434328 return (seq[pos:pos + size] for pos in range(0, len(seq), size)) def insert_with_progress(df, engine, table_name: str, chunksize=None, reset_index=True): if reset_index: dfi = df.reset_index() else: dfi = df if chunksize is None: chunksize = int(len(dfi) / 10) # 10% with tqdm(total=len(dfi)) as pbar: for i, cdf in enumerate(chunker(dfi, chunksize)): cdf.to_sql(con=engine, name=table_name, if_exists="append", index=False) pbar.update(chunksize) def extract_one_prcp_to_sql(filename: str, by_year_path: str, engine, table_name: str): keys = ['station', 'dateto'] df = df_file(filename, by_year_path) logging.debug(f"dateframe {df.shape} loaded") df_sel = df >> mask(X.element == 'PRCP') >> transmute(station=X.station, dateto=X.dateto, prcp_mm=X.value / 10) logging.debug(f"prcp data {df_sel.shape} extracted") dmin, dmax = (df_sel['dateto'].min(), df_sel['dateto'].max()) df_sorted = df_sel.set_index(keys) sql_mirror = ( "select station, dateto\n" f"from {table_name}\n" f"where dateto between '{dmin}' and '{dmax}'\n" "order by station, dateto" ) df_mirror = pd.DataFrame(engine.execute(sql_mirror).fetchall(), columns=keys).set_index(keys) df_mirror['indb'] = True logging.debug(f"mirror data {df_mirror.shape} extracted") if df_mirror.shape[0] == 0: df_joined = df_sorted df_joined['indb'] = False else: df_joined = df_sorted.join(df_mirror, on=keys, how='left', sort=True) df_joined['indb'] = df_joined['indb'].fillna(False) if (~df_joined['indb']).sum() > 0: df_filtered = df_joined >> mask(~X.indb) df_increment = df_filtered >> select(X.prcp_mm) logging.debug(f"sql insert to {table_name} in progress") insert_with_progress(df_increment, engine, table_name, chunksize=100) logging.debug(f"insert to {table_name} completed") else: logging.debug("increment is empty") def extract_all_prcp_to_sql(by_year_path: str, engine, table_name: str): files = sorted(os.listdir(by_year_path)) nfiles = len(files) for i, filename in enumerate(files): logging.debug(f"{i + 1}/{nfiles} {filename}") extract_one_prcp_to_sql(filename, by_year_path, engine, table_name) logging.debug("extract completed") def find_topk_nearest(k: int, station, index, x1, sortindex1, x2, sortindex2) -> List[dict]: nst = len(index) # total number of stations point = (station.latitude, station.longitude) i1 = np.where(x1[sortindex1] == point[0])[0][0] i2 = np.where(x2[sortindex2] == point[1])[0][0] n1 = 100 # intial perimeter, expert guess, works on ruzyne n2 = 100 # intial perimeter, expert guess, works on ruzyne inperim = np.zeros(nst, dtype=bool) ninp = 1 while ninp < k + 1: i1lb = max(i1 - n1, 0) i1ub = min(i1 + n1, nst - 1) x1lb, x1ub = (x1[sortindex1][i1lb], x1[sortindex1][i1ub]) i2lb = max(i2 - n2, 0) i2ub = min(i2 + n2, nst - 1) x2lb, x2ub = (x2[sortindex2][i2lb], x2[sortindex2][i2ub]) inperim = (x1 >= x1lb) & (x1 <= x1ub) & (x2 >= x2lb) & (x2 <= x2ub) ninp = np.sum(inperim) n1 *= 2 n2 *= 2 distvec = np.array([geodesic(point, station_point).km for station_point in zip(x1[inperim], x2[inperim])]) indout = np.argsort(distvec)[1:k + 1] result = [{'station': stid, 'dist_km': disti} for stid, disti in zip(index[indout], distvec[indout])] return result def find_nearest_stations(stations: pd.DataFrame) -> Dict[str, List]: topk = 3 x1 = stations['latitude'].values x2 = stations['longitude'].values sortindex1 = np.argsort(x1) sortindex2 = np.argsort(x2) result = {} for station in tqdm(stations.itertuples(), total=len(stations)): topn_list = find_topk_nearest( k=topk, station=station, index=stations.index, x1=x1, sortindex1=sortindex1, x2=x2, sortindex2=sortindex2) result[station.Index] = topn_list return result def get_nearest_stations() -> Dict[str, list]: with open('../../data/station/nearest_stations.json', 'r') as file: nearest = json.load(file) return nearest def df_station(station: str, engine=None) -> pd.DataFrame: if engine is None: engine = create_engine('postgresql://postgres:@localhost/ghcn') q = engine.execute(f"select * from prcp where station='{station}' order by dateto").fetchall() df = pd.DataFrame(q, columns=['station', 'dateto', 'prcp_mm']) return df.set_index(['station', 'dateto']) def make_day_index(year: int) -> pd.DataFrame: """ Make calendar with day index where 0=last day of the previous year, 1=first day of the year. It spans the current year and two previous years, so the range is -730 to +365, which is 1095 days for one station and year. """ start_date = date(year-2, 1, 1) end_date = date(year, 12, 31) zero_date = datetime(year-1, 12, 31) date_axis = pd.date_range(start=start_date, end=end_date, freq='D') day_index = (date_axis - zero_date).days calendar = pd.DataFrame({ 'year': year, 'dateto': [date(d.year, d.month, d.day) for d in date_axis], 'day_index': day_index, }, columns=['year', 'dateto', 'day_index']) # logging.debug(f"calendar with {len(date_axis)} days from {date_axis[0]} to {date_axis[-1]}") return calendar def calc_reference_station_year(prcp: pd.DataFrame, year: int) -> pd.DataFrame: keys = ['station', 'dateto'] day_index = make_day_index(year) day_index['station'] = prcp.index[0][0] day_index = day_index.set_index(keys) ref = day_index.join(prcp) ref['cum_prcp'] = np.nancumsum(ref['prcp_mm'].astype(float)) day_observed = ref['prcp_mm'].notnull() cum_days_observed = np.cumsum(day_observed) cum_days_available = np.arange(1, len(ref)+1) ref['cum_fillrate'] = cum_days_observed / cum_days_available ref['reference_prcp'] = ref['cum_prcp'] / ref['cum_fillrate'] # ref.at[ref['cum_fillrate'] < 0.8, 'reference_prcp'] = np.nan return ref def calc_reference_station(prcp: pd.DataFrame) -> pd.DataFrame: years = np.arange(1981, 2010+1) ref_list = [] for year in years: ref_year = calc_reference_station_year(prcp, year) ref_list.append(ref_year) ref = pd.concat(ref_list, axis=0) return ref def reference_quantiles(reference: pd.DataFrame) -> pd.DataFrame: qq = np.array([0.00, 0.25, 0.50, 0.75, 1.00]) cdf_prcp = ECDF() cdf_fill = ECDF() qlist = [] keys = ['station', 'day_index'] for gkeys, gref in reference.groupby(keys): if gref.empty or gref['reference_prcp'].notnull().sum() == 0: qprcp = np.full(5, np.nan) qfill = np.full(5, np.nan) else: cdf_prcp.fit(gref['reference_prcp'], weights=gref['cum_fillrate']) qprcp = cdf_prcp.quantile(qq) cdf_fill.fit(gref['cum_fillrate']) qfill = cdf_fill.quantile(qq) row = (*gkeys, *qprcp, *qfill) qlist.append(row) cols = [ *keys, 'prcp_min', 'prcp_p25', 'prcp_p50', 'prcp_p75', 'prcp_max', 'fill_min', 'fill_p25', 'fill_p50', 'fill_p75', 'fill_max', ] qdf = pd.DataFrame(qlist, columns=cols).set_index(keys) return qdf def calc_reference_quantiles(prcp: pd.DataFrame) -> pd.DataFrame: """Composition of calc_reference_station and reference_quantiles.""" # This makes sure that we do not use the reference dataset directly, just the quantiles ref = calc_reference_station(prcp) q = reference_quantiles(ref) return q def load_reference_quantiles(station: str, engine) -> pd.DataFrame: """Load reference quantiles from database.""" q = engine.execute(f"select * from reference where station='{station}'").fetchall() cols = [ 'station', 'day_index', 'prcp_min', 'prcp_p25', 'prcp_p50', 'prcp_p75', 'prcp_max', 'fill_min', 'fill_p25', 'fill_p50', 'fill_p75', 'fill_max', ] df = pd.DataFrame(q, columns=cols).set_index(keys=['station', 'day_index']) return df def calc_cumprcp(prcp: pd.DataFrame, year: int) -> pd.DataFrame: data_end_date = prcp.index.get_level_values('dateto')[-1] cprcp = calc_reference_station_year(prcp, year) # reuse the same code as for the reference cprcp.columns = ['year', 'day_index', 'prcp_mm', 'cum_prcp', 'cum_fillrate', 'ytd_prcp'] idx = pd.IndexSlice return cprcp.loc[idx[:, :data_end_date], :] def drought_index(cum_prcp: float, reference_cum_prcp: np.ndarray) -> float: """Calculate drought index from the cumulative precipitation and the reference values.""" cdf = ECDF() cdf.fit(reference_cum_prcp) curr_cdf = cdf.eval(np.array(cum_prcp)) curr_drought_index = 2 * (0.5 - curr_cdf) return curr_drought_index def current_drought_rate(refq: pd.DataFrame, curr_cprcp: pd.Series) -> float: if refq.empty: curr_drought_rate = np.nan else: curr_station = refq.index[0][0] curr_day_index = curr_cprcp['day_index'] curr_ytd_prcp = curr_cprcp['ytd_prcp'] refq_columns = ['prcp_min', 'prcp_p25', 'prcp_p50', 'prcp_p75', 'prcp_max'] refq_prcp = refq.loc[(curr_station, curr_day_index), refq_columns].values if len(refq_prcp) > 0: curr_drought_rate = drought_index(curr_ytd_prcp, refq_prcp.flatten()) else: curr_drought_rate = np.nan return curr_drought_rate def current_fillrate_cdf(refq: pd.DataFrame, curr_cprcp: pd.Series) -> float: curr_station = refq.index[0][0] curr_day_index = curr_cprcp['day_index'] curr_fillrate = curr_cprcp['cum_fillrate'] refq_columns = ['fill_min', 'fill_p25', 'fill_p50', 'fill_p75', 'fill_max'] ref_fillrate = refq.loc[(curr_station, curr_day_index), refq_columns].values if len(ref_fillrate) > 0: cdf = ECDF() cdf.fit(ref_fillrate.flatten()) curr_fillrate_cdf = cdf.eval(curr_fillrate) else: curr_fillrate_cdf = np.nan return curr_fillrate_cdf def station_label(station: pd.Series) -> str: coords = f"{station.latitude:.3f}, {station.longitude:.3f}, {station.elevation:.0f}" stlabel = f"{station.continent_name}/{station.country_name}/{station.station_name} ({coords})" return stlabel def nice_ylim(y: float) -> float: """Guess the ylim which is proportional to the value.""" step = 10.0 ** np.round(np.log10(0.1*y)) ub = step * np.ceil(y / step) return ub def cum_prcp_plot_matplotlib( stlabel: str, rdf: pd.DataFrame, cprcp: pd.DataFrame, curr_drought_rate: float ): """ Plot cumulative precipitation with Matplotlib. Deprecated in favor of cum_prcp_plot. :param stlabel: :param rdf: :param cprcp: :param curr_drought_rate: :return: """ f = plt.figure(figsize=(12, 12)) if not rdf.empty and rdf['prcp_min'].notnull().sum() > 0: prcp_ub = nice_ylim(rdf['prcp_max'].iloc[-1]) xx = rdf['dateto'] plt.fill_between(x=xx, y1=0, y2=rdf['prcp_min'], color='red', linewidth=0.0, alpha=0.5) plt.fill_between(x=xx, y1=rdf['prcp_min'], y2=rdf['prcp_p25'], color='orange', linewidth=0.0, alpha=0.5) plt.fill_between(x=xx, y1=rdf['prcp_p25'], y2=rdf['prcp_p75'], color='green', linewidth=0.0, alpha=0.5) plt.fill_between(x=xx, y1=rdf['prcp_p75'], y2=rdf['prcp_max'], color='cyan', linewidth=0.0, alpha=0.5) plt.fill_between(x=xx, y1=rdf['prcp_max'], y2=prcp_ub, color='blue', linewidth=0.0, alpha=0.5) plt.plot(xx, rdf['prcp_p50'], c='grey') if not cprcp.empty: plt.plot(cprcp.index.get_level_values('dateto'), cprcp['ytd_prcp'], c='red', linewidth=3) ax = plt.gca() ax.set_title(f"{stlabel}: current drought rate is {100 * curr_drought_rate:.0f}%") ax.set_ylabel('3rd year cumulative precipitation in mm') ax.grid(True) return f def cum_prcp_plot( stlabel: str, rdf: pd.DataFrame, cprcp: pd.DataFrame, curr_drought_rate: float ): """ Plot cumulative precipitation with Bokeh. :param stlabel: :param rdf: :param cprcp: :param curr_drought_rate: :return: """ src_ref = ColumnDataSource(rdf) src_cur = ColumnDataSource(cprcp.reset_index()) p = figure( plot_width=800, plot_height=800, title=f"{stlabel}: current drought index is {100 * curr_drought_rate:.0f}%", y_axis_label="3rd year cumulative precipitation in mm", x_axis_type='datetime', ) if not rdf.empty and rdf['prcp_min'].notnull().sum() > 0: prcp_ub = nice_ylim(rdf['prcp_max'].iloc[-1]) amin = VArea(x="dateto", y1=0, y2="prcp_min", fill_color="red", fill_alpha=0.5) ap25 = VArea(x="dateto", y1="prcp_min", y2="prcp_p25", fill_color="orange", fill_alpha=0.5) ap50 = VArea(x="dateto", y1="prcp_p25", y2="prcp_p75", fill_color="green", fill_alpha=0.5) ap75 = VArea(x="dateto", y1="prcp_p75", y2="prcp_max", fill_color="cyan", fill_alpha=0.5) amax = VArea(x="dateto", y1="prcp_max", y2=prcp_ub, fill_color="blue", fill_alpha=0.5) lp50 = Line(x="dateto", y="prcp_p50", line_color='grey', line_width=3) p.add_glyph(src_ref, amin) p.add_glyph(src_ref, ap25) p.add_glyph(src_ref, ap50) p.add_glyph(src_ref, ap75) p.add_glyph(src_ref, amax) rref = p.add_glyph(src_ref, lp50) ttp_ref = [ ("Date", "@dateto{%F}"), ("Day Index", "@day_index"), ("Precipitation min", "@prcp_min{0.}"), ("Precipitation p25", "@prcp_p25{0.}"), ("Precipitation p50", "@prcp_p50{0.}"), ("Precipitation p75", "@prcp_p75{0.}"), ("Precipitation max", "@prcp_max{0.}"), ] hover_ref = HoverTool(renderers=[rref], tooltips=ttp_ref, formatters={"@dateto": "datetime"}) p.add_tools(hover_ref) if not cprcp.empty: lcur = Line(x='dateto', y='ytd_prcp', line_color='red', line_width=3) rcur = p.add_glyph(src_cur, lcur) ttp_cur = [ ("Date", "@dateto{%F}"), ("Day Index", "@day_index"), ("Precipitation that day (mm)", "@prcp_mm{0.}"), ("Precipitation 3rd year cumulative observed (mm)", "@cum_prcp{0.}"), ("Fill rate 3rd year cumulative", "@cum_fillrate{0.000}"), ("Precipitation 3rd year cumulative predicted (mm)", "@ytd_prcp{0.}"), ] hover_cur = HoverTool(renderers=[rcur], tooltips=ttp_cur, formatters={"@dateto": "datetime"}) p.add_tools(hover_cur) return p def cum_fillrate_plot( stlabel: str, rdf: pd.DataFrame, cprcp: pd.DataFrame, curr_fillrate: float, curr_fillrate_cdf: float, ): f = plt.figure(figsize=(16, 9)) if not cprcp.empty: plt.plot(cprcp.index.get_level_values('dateto'), cprcp['cum_fillrate'], c='red', linewidth=3) if not rdf.empty: plt.fill_between(rdf['dateto'], y1=rdf['fill_min'], y2=rdf['fill_max'], color='lightgray', alpha=0.5) plt.fill_between(rdf['dateto'], y1=rdf['fill_p25'], y2=rdf['fill_p75'], color='darkgray', alpha=0.5) plt.plot(rdf['dateto'], rdf['fill_p50'], color='gray') ax = plt.gca() ax.set_ylim(0, 1) title = f"{stlabel}: current fill rate is {curr_fillrate:.2f} which is {100 * curr_fillrate_cdf:.0f} percentile" ax.set_title(title) ax.set_ylabel('fill rate') ax.grid(True) return f def totals_barchart_matplotlib(dfy: pd.DataFrame): """Deprecated in favor of totals_barchart.""" f = plt.figure(figsize=(12, 12)) ax = plt.gca() ax.set_ylabel("annual precipitation in mm") ax.set_title(f"Yearly precipitation totals") if not dfy.empty: xx = dfy['year'].values yy = dfy['prcp_mm'].values / 10 dd = dfy['observed_days'] x1 = np.min(xx) x2 = np.max(xx) mx = np.mean(xx) my = np.mean(yy) plt.bar(xx, yy, width=0.8) plt.step(xx, dd, c='red') plt.plot([x1, x2], [my, my], color='blue') ax.annotate( f"{my:.0f}", xy=(mx, my), xytext=(0, 3), # 3 points vertical offset textcoords="offset points", ha='center', va='bottom', fontsize='x-large', color='blue', ) return f def totals_barchart(df: pd.DataFrame): dfy = df.copy() dfy['prcp_mm'] = df.prcp_mm / 10 dfy['available_days'] = 365 + (dfy.year % 4 == 0) dfy['fill_rate'] = dfy.observed_days / dfy.available_days dfy['prcp_pred'] = dfy.prcp_mm / dfy.fill_rate prcp_pred_mean = dfy.prcp_pred.mean() dfy['prcp_pred_mean'] = prcp_pred_mean f = figure( plot_width=800, plot_height=800, title=f"Yearly precipitation totals, mean={prcp_pred_mean:.0f}mm", y_axis_label="annual precipitation in mm", ) if not dfy.empty: src = ColumnDataSource(dfy) bobs = VBar(x='year', top='prcp_mm', fill_color='blue', line_color='blue', width=0.8) bpre = VBar(x='year', bottom='prcp_mm', top='prcp_pred', fill_color='lightblue', line_color='blue', width=0.8) lpre = Line(x='year', y='prcp_pred_mean', line_color='darkblue', line_width=3) f.add_glyph(src, bobs) f.add_glyph(src, bpre) f.add_glyph(src, lpre) ttp = [ ("Year", "@year"), ("Precipitation observed (mm)", "@prcp_mm{0.}"), ("Observed days", "@observed_days"), ("Available days", "@available_days"), ("Fill rate", "@fill_rate{0.000}"), ("Precipitation predicted (mm)", "@prcp_pred{0.}"), ] hover_tool = HoverTool(tooltips=ttp) f.add_tools(hover_tool) return f def drought_rate_data(stid: str, year: int, engine=None) -> tuple: prcp = df_station(stid, engine) if not prcp.empty: if engine is None: refq = calc_reference_quantiles(prcp) else: refq = load_reference_quantiles(stid, engine) data_end_date = prcp.index.get_level_values('dateto')[-1] day_index = make_day_index(year) rdf = day_index.merge(refq, on='day_index', how='left') >> mask(X.dateto <= data_end_date) if engine is None: cprcp = calc_cumprcp(prcp, year) else: cprcp = calc_cumprcp(prcp, year) # TODO load from db if not cprcp.empty: curr_cprcp = cprcp.iloc[-1, :] curr_fillrate = curr_cprcp['cum_fillrate'] if refq.empty: curr_drought_rate = np.nan curr_fillrate_cdf = np.nan else: curr_drought_rate = current_drought_rate(refq, curr_cprcp) curr_fillrate_cdf = current_fillrate_cdf(refq, curr_cprcp) else: curr_drought_rate = np.nan curr_fillrate = np.nan curr_fillrate_cdf = np.nan else: rdf = pd.DataFrame() cprcp = pd.DataFrame() curr_drought_rate = np.nan curr_fillrate = np.nan curr_fillrate_cdf = np.nan return rdf, cprcp, curr_drought_rate, curr_fillrate, curr_fillrate_cdf def sql_engine(): engine = create_engine('postgres://postgres:@localhost/ghcn') return engine def get_stations_noref(engine, stations: pd.DataFrame) -> pd.DataFrame: cols = ['station', 'dispatched_at', 'completed_at'] sql_noref = ( f"select {', '.join(cols)}\n" "from reference_job\n" "where completed_at is null" ) station_noref = pd.DataFrame(engine.execute(sql_noref).fetchall(), columns=cols).set_index('station') station_coord = station_noref.join(stations) lat = station_coord.latitude lon = station_coord.longitude center_point = (49.9629345, 14.0600897) # x=14.0600897&y=49.9629345 = <NAME> 1005 station_coord['perimeter_km'] = np.array([geodesic(center_point, station_point).km for station_point in zip(lat, lon)]) return station_coord.sort_values(by='perimeter_km') def ded_prcp(engine) -> date: sql_query = ( "select max(dateto) as ded\n" "from prcp" ) df = pd.DataFrame(engine.execute(sql_query).fetchall(), columns=['ded']) data_end_dt = df['ded'].iat[0] data_end_date = date(data_end_dt.year, data_end_dt.month, data_end_dt.day) logging.debug(f"data_end_date={data_end_date}") return data_end_date def ded_cump(engine, year: int) -> tuple: sql_query = ( "select max(dateto) as ded, max(day_index) as dei\n" "from cumprcp\n" f"where year={year}" ) df = pd.DataFrame(engine.execute(sql_query).fetchall(), columns=['ded', 'dei']) data_end_dt = df['ded'].iat[0] data_end_index = df['dei'].iat[0] if data_end_dt is None: data_end_date = None else: data_end_date = date(data_end_dt.year, data_end_dt.month, data_end_dt.day) logging.debug(f"cump_end_date={data_end_date}") return data_end_date, data_end_index def prcp_dateto(engine, dateto: date) -> pd.DataFrame: """Select all rows from prcp table as of dateto.""" sql_query = f"select station, cast(prcp_mm as float) as prcp_mm from prcp where dateto=date'{dateto.isoformat()}'" logging.debug(sql_query) df = pd.DataFrame(engine.execute(sql_query).fetchall(), columns=['station', 'prcp_mm']) return df def increment_cumprcp(engine, year: int, day_index: int, dateto: date, cum_days_available: int): """Insert new records to cumprcp for the spacified day assuming that the previous day is there.""" cols_previous = ['station', 'year', 'day_index', 'dateto', 'cum_days_observed', 'cum_prcp'] sql_previous = f"select {', '.join(cols_previous)} from cumprcp where year={year} and day_index={day_index - 1}" cumprcp_previous = pd.DataFrame(engine.execute(sql_previous).fetchall(), columns=cols_previous) assert not cumprcp_previous.empty prcp = prcp_dateto(engine, dateto) cols_both = ['station', 'year'] cumprcp = cumprcp_previous[cols_both].merge(prcp, how='left', on='station') cumprcp['day_index'] = day_index cumprcp['dateto'] = dateto cumprcp['flag_observed'] = cumprcp.prcp_mm.notnull() cumprcp['cum_days_observed'] = cumprcp_previous.cum_days_observed + cumprcp.flag_observed cumprcp['cum_fillrate'] = cumprcp.cum_days_observed / cum_days_available cumprcp['cum_prcp'] = cumprcp_previous.cum_prcp + cumprcp.prcp_mm.fillna(0) cumprcp['cum_prcp_pred'] = cumprcp.cum_prcp / cumprcp.cum_fillrate cols_out = [ 'station', 'year', 'day_index', 'dateto', 'flag_observed', 'cum_days_observed', 'cum_fillrate', 'cum_prcp', 'cum_prcp_pred', ] insert_with_progress(cumprcp[cols_out], engine, table_name='cumprcp', reset_index=False) def update_cumprcp(engine): """Update table cumprcp if new data is available in prcp table.""" stations = load_stations() prcp_end_date = ded_prcp(engine) year = prcp_end_date.year day_index = make_day_index(year) first_day_index = day_index['day_index'].iat[0] cump_end_date, cump_end_index = ded_cump(engine, year) if cump_end_date is None: # create new year skeleton dateto0 = day_index['dateto'].iat[0] logging.debug(dateto0) prcp0 = prcp_dateto(engine, dateto0) cump0 = stations >> left_join(prcp0, by='station') flag_observed = cump0.prcp_mm.notnull() skeleton = pd.DataFrame({ 'station': stations.index, 'year': year, 'day_index': first_day_index, 'dateto': dateto0, 'flag_observed': flag_observed, 'cum_days_observed': flag_observed.astype(int), 'cum_fillrate': flag_observed.astype(float), 'cum_prcp': cump0.prcp_mm.fillna(0), 'cum_prcp_pred': cump0.prcp_mm, }) insert_with_progress(skeleton, engine, table_name='cumprcp', reset_index=False) cump_end_date = dateto0 day_index_todo = day_index.loc[(day_index.dateto > cump_end_date) & (day_index.dateto <= prcp_end_date), :] for x in day_index_todo.itertuples(): logging.debug(x) cum_days_available = x.day_index - first_day_index + 1 increment_cumprcp(engine, x.year, x.day_index, x.dateto, cum_days_available) logging.debug("completed") def do_worker_job(engine, station_id: str): if station_id: prcp = df_station(station_id) if not prcp.empty: refq = calc_reference_quantiles(prcp) if not refq.empty: insert_with_progress(refq, engine, table_name='reference', chunksize=2000) return def make_station_tree(stations: pd.DataFrame) -> Tuple[pd.DataFrame, pd.DataFrame]: """All nodes of the stations tree are searcheable in the autocomplete by node_name.""" def node_name_station(station_record: NamedTuple) -> str: name = f"{station_record.station_name} (station in {station_record.country_name})" return name def node_name_country(station_record: NamedTuple) -> str: name = f"{station_record.country_name} (country in {station_record.continent_name})" return name station_name = pd.Series([node_name_station(x) for x in stations.itertuples()]) if station_name.is_unique: logging.debug("tree nodes are unique") else: logging.error("tree nodes are not unique") freq = station_name.value_counts() ndup = np.sum(freq > 1) logging.debug(f"{ndup} duplicated names") for index, value in tqdm(freq[:ndup].iteritems(), total=ndup): # logging.debug(f"{index}: {value}x") # deduplication - add i/n at the end of each name dupidx = np.flatnonzero(station_name == index) for i, (idx, ndname) in enumerate(station_name.iloc[dupidx].iteritems()): # logging.debug(f"{idx}: {ndname} {i+1}/{value}") station_name.at[idx] = f"{ndname} {i+1}/{value}" country_name = pd.Series([node_name_country(x) for x in stations.itertuples()]) continent_name = stations['continent_name'] node_name = pd.concat([station_name, country_name, continent_name], axis=0) stidx = stations.index.values station = np.concatenate((stidx, stidx, stidx), axis=0) node_station = pd.DataFrame({ 'node_name': node_name, 'station': station, }) nvc = node_station['node_name'].value_counts() tree = pd.DataFrame({ 'node_name': nvc.index, 'num_stations': nvc.values, }) return tree, node_station def refresh_drought(engine): """Refresh table drought from cumprcp and reference for the last day_index available.""" sql_year = "select max(year) from cumprcp" max_year = engine.execute(sql_year).fetchone()[0] logging.debug(f"max_year={max_year}") sql_index = f"select max(day_index) from cumprcp where year = {max_year}" max_day_index = engine.execute(sql_index).fetchone()[0] logging.debug(f"max_day_index={max_day_index}") last_cumprcp_cols = ["station", "cum_prcp_pred", "cum_fillrate"] sql_last_cumprcp = ( f"select {', '.join(last_cumprcp_cols)} " f"from cumprcp where year = {max_year} and day_index = {max_day_index} " f"and {' and '.join([c + ' is not null' for c in last_cumprcp_cols])}" ) logging.debug(sql_last_cumprcp) last_cumprcp = pd.DataFrame( engine.execute(sql_last_cumprcp).fetchall(), columns=last_cumprcp_cols ).set_index('station') logging.debug(f"last_cumprcp={last_cumprcp.shape}") reference_prcp_cols = ["prcp_min", "prcp_p25", "prcp_p50", "prcp_p75", "prcp_max"] last_reference_cols = ["station"] + reference_prcp_cols sql_last_reference = ( f"select {', '.join(last_reference_cols)} " f"from reference where day_index = {max_day_index} " f"and {' and '.join([c + ' is not null' for c in reference_prcp_cols])}" ) logging.debug(sql_last_reference) last_reference = pd.DataFrame( engine.execute(sql_last_reference).fetchall(), columns=last_reference_cols ).set_index('station') logging.debug(f"last_reference={last_reference.shape}") drought = last_reference.join(last_cumprcp, how='inner') logging.debug(f"drought={drought.shape}") drought['drought_index'] = [drought_index(x.cum_prcp_pred, x[reference_prcp_cols]) for s, x in drought.iterrows()] engine.execute("truncate table drought") out_df = drought.reset_index() >> select(X.station, X.drought_index, X.cum_prcp_pred, X.cum_fillrate) logging.debug(f"out_df={out_df.shape}") insert_with_progress(out_df, engine, table_name='drought', reset_index=False) def get_drought(engine) -> pd.DataFrame: cols = ["station", "drought_index", "cum_prcp_pred", "cum_fillrate"] df = pd.DataFrame(engine.execute("select * from drought").fetchall(), columns=cols).set_index("station") return df def get_drought_stats(drought: pd.DataFrame) -> tuple: """Calculate stats from the not aggregated drought data.""" flag_dry = (drought.drought_index >= 0.5) num_dry = np.sum(flag_dry) num_stations = len(drought) if num_stations > 0: drought_rate = num_dry / num_stations else: drought_rate = np.nan return num_stations, num_dry, drought_rate def aggregate_drought(drought: pd.DataFrame, agg_stations=50) -> pd.DataFrame: """Return aggd, num_dry, num_stations.""" drought = drought.sort_values(by='drought_index') num_stations = len(drought) bucket_size = np.ceil(num_stations / agg_stations) drought['bucket_mark'] = (np.arange(0, num_stations) // bucket_size + 1) * bucket_size aggd = drought >> group_by(X.bucket_mark) >> summarize( drought_index=X.drought_index.mean(), cum_fillrate=X.cum_fillrate.mean(), bucket_size=n(X.drought_index), ) aggd = aggd.set_index('bucket_mark') aggd.index = aggd.index.set_names('index') return aggd def drought_add_facecolor(drought: pd.DataFrame) -> pd.DataFrame: """Add facecolor column before drought plot.""" bar_colors = np.array(['blue', 'cyan', 'green', 'orange', 'red']) drought_index_band = pd.cut(drought.drought_index, [-1.0, -0.99, -0.5, +0.5, +0.99, +1.001], right=False) drought['facecolor'] = bar_colors[drought_index_band.cat.codes.values] if "bucket_size" in drought.columns: drought['barwidth'] = drought['bucket_size'] * 0.8 else: drought['barwidth'] = 0.8 return drought def drought_rate_plot_core(drought: pd.DataFrame, drought_stats: tuple, tooltips: list): num_stations, num_dry, drought_rate = drought_stats src = ColumnDataSource(drought) p = figure( plot_width=1600, plot_height=600, title=f"Drought rate is {100 * drought_rate:.0f}%={num_dry}/{num_stations}.", y_axis_label="Drought Index", x_axis_label="Station Rank by Drought Index", ) p.vbar( x="index", top="drought_index", width="barwidth", alpha="cum_fillrate", fill_color="facecolor", line_color=None, source=src) p.y_range.start = -1.0 p.y_range.end = +1.0 p.add_tools(HoverTool(tooltips=tooltips)) p.xgrid.grid_line_color = None return p def drought_rate_plot(drought: pd.DataFrame): drought_stats = get_drought_stats(drought) ttp = [ ("cum_prcp_predicted", "@cum_prcp_pred{00.}"), ("cum_fillrate", "@cum_fillrate{0.00}"), ("id", "@station"), ("station", "@station_name"), ("country", "@country_name"), ("elevation", "@elevation{0.}"), ] plotdf = drought.sort_values(by='drought_index').reset_index() p = drought_rate_plot_core(plotdf, drought_stats, ttp) return p def drought_rate_plot_agg(drought: pd.DataFrame, agg_stations=50): drought_stats = get_drought_stats(drought) aggd = aggregate_drought(drought, agg_stations=agg_stations) ttp = [ ("Mean drought index", "@drought_index{0.000}"), ("Bucket size", "@bucket_size"), ("Mean fill rate", "@cum_fillrate{0.000}"), ] aggd = drought_add_facecolor(aggd) p = drought_rate_plot_core(aggd, drought_stats, ttp) return p def update_yearly_totals(year: int): prcp_path = '../../data/prcp' out_file = '../../data/yearly_totals/prcp_totals.csv' logging.debug(f"current_year={year}") prcp = df_prcp(year, prcp_path) totals = prcp >> group_by(X.station) >> summarize( prcp_mm=X.prcp.sum(), observed_days=n(X.prcp), ) >> mutate(year=year) logging.debug(f"{len(totals)} totals calculated") df1 = pd.read_csv(out_file) logging.debug(f"{len(df1)} records read from {out_file}") df2 = df1 >> mask(X.year < year) logging.debug(f"{len(df2)} records after deleting year {year}") logging.debug(f"{len(totals)} records of current year {year} to be added") df_totals = pd.concat([df2, totals], axis=0).sort_values(by=['station', 'year']) df_totals.to_csv(out_file, index=False) logging.debug(f"{len(df_totals)} records saved to {out_file}") def wgs84_epsg3857(wgs84: tuple) -> tuple: """ Convert (longitude, latitude) coordinates in WGS84 to EPSG 3857 Mercator coordinates. See https://epsg.io/3857 for the definition. See https://epsg.io/transform#s_srs=4326&t_srs=3857&x=-4.2325468&y=50.4211273 to check. """ lon, lat = wgs84 r_major = 6378137.000 x = r_major * np.radians(lon) scale = x / lon y = 180.0 / np.pi * np.log(np.tan(np.pi / 4.0 + lat * (np.pi / 180.0) / 2.0)) * scale return x, y def good_map_limits(x: pd.Series, margin_rel=0.1, margin_abs=50e3) -> tuple: """Calculate good map limits for the given dimesion.""" xmin = x.min() xmax = x.max() xdel = xmax - xmin xoff = max(margin_rel * xdel, margin_abs) return xmin - xoff, xmax + xoff def drought_map(dfm: pd.DataFrame): """Draw Bokeh map of points""" dfm['alpha'] = 0.3 + 0.7 * dfm.cum_fillrate.fillna(0) xy = [wgs84_epsg3857((s.longitude, s.latitude)) for s in dfm.itertuples()] dfm['x'] = [t[0] for t in xy] dfm['y'] = [t[1] for t in xy] tile_provider = get_provider(STAMEN_TERRAIN) xrange = good_map_limits(dfm.x) yrange = good_map_limits(dfm.y) col_source = ColumnDataSource(dfm) p = figure( plot_width=1600, plot_height=800, x_range=xrange, y_range=yrange, x_axis_type="mercator", y_axis_type="mercator", ) p.add_tile(tile_provider) p.circle(x='x', y='y', size=15, color='facecolor', alpha='alpha', source=col_source) ttp = [ ("cum_prcp_predicted", "@cum_prcp_pred{00.}"), ("cum_fillrate", "@cum_fillrate{0.00}"), ("id", "@station"), ("station", "@station_name"), ("country", "@country_name"), ("elevation", "@elevation{0.}"), ] hover_tool = HoverTool(tooltips=ttp) p.add_tools(hover_tool) return p
[ "numpy.sum", "bokeh.models.Line", "numpy.ones", "dfply.arrange", "numpy.argsort", "matplotlib.pyplot.figure", "numpy.arange", "numpy.interp", "matplotlib.pyplot.fill_between", "logging.error", "numpy.max", "datetime.timedelta", "numpy.radians", "pandas.date_range", "datetime.date.today",...
[((2480, 2525), 'logging.debug', 'logging.debug', (['f"""ftp_filename={ftp_filename}"""'], {}), "(f'ftp_filename={ftp_filename}')\n", (2493, 2525), False, 'import logging\n'), ((2530, 2567), 'logging.debug', 'logging.debug', (['f"""save_dir={save_dir}"""'], {}), "(f'save_dir={save_dir}')\n", (2543, 2567), False, 'import logging\n'), ((2578, 2672), 'ftplib.FTP', 'ftplib.FTP', ([], {'host': '"""ftp.ncdc.noaa.gov"""', 'timeout': '(10.0)', 'user': '"""anonymous"""', 'passwd': '"""<PASSWORD>"""'}), "(host='ftp.ncdc.noaa.gov', timeout=10.0, user='anonymous', passwd\n ='<PASSWORD>')\n", (2588, 2672), False, 'import ftplib\n'), ((2672, 2709), 'logging.debug', 'logging.debug', (['"""FTP server connected"""'], {}), "('FTP server connected')\n", (2685, 2709), False, 'import logging\n'), ((2771, 2807), 'os.path.join', 'os.path.join', (['save_dir', 'ftp_filename'], {}), '(save_dir, ftp_filename)\n', (2783, 2807), False, 'import os\n'), ((2812, 2853), 'logging.debug', 'logging.debug', (['f"""downloading {save_path}"""'], {}), "(f'downloading {save_path}')\n", (2825, 2853), False, 'import logging\n'), ((2957, 2997), 'logging.debug', 'logging.debug', (['f"""downloaded {save_path}"""'], {}), "(f'downloaded {save_path}')\n", (2970, 2997), False, 'import logging\n'), ((3073, 3103), 'os.path.join', 'os.path.join', (['folder', 'filename'], {}), '(folder, filename)\n', (3085, 3103), False, 'import os\n'), ((3108, 3147), 'logging.debug', 'logging.debug', (['f"""unzipping {read_path}"""'], {}), "(f'unzipping {read_path}')\n", (3121, 3147), False, 'import logging\n'), ((3156, 3182), 'gzip.open', 'gzip.open', (['read_path', '"""rb"""'], {}), "(read_path, 'rb')\n", (3165, 3182), False, 'import gzip\n'), ((3229, 3267), 'logging.debug', 'logging.debug', (['f"""unzipped {read_path}"""'], {}), "(f'unzipped {read_path}')\n", (3242, 3267), False, 'import logging\n'), ((3461, 3491), 'os.path.join', 'os.path.join', (['folder', 'filename'], {}), '(folder, filename)\n', (3473, 3491), False, 'import os\n'), ((3496, 3547), 'logging.debug', 'logging.debug', (['f"""unzipping and reading {read_path}"""'], {}), "(f'unzipping and reading {read_path}')\n", (3509, 3547), False, 'import logging\n'), ((3809, 3843), 'logging.debug', 'logging.debug', (['f"""read {read_path}"""'], {}), "(f'read {read_path}')\n", (3822, 3843), False, 'import logging\n'), ((4178, 4204), 'logging.debug', 'logging.debug', (['"""completed"""'], {}), "('completed')\n", (4191, 4204), False, 'import logging\n'), ((4432, 4502), 'logging.debug', 'logging.debug', (['f"""{df_sel.shape[0]} out of {df.shape[0]} rows selected"""'], {}), "(f'{df_sel.shape[0]} out of {df.shape[0]} rows selected')\n", (4445, 4502), False, 'import logging\n'), ((4635, 4673), 'logging.debug', 'logging.debug', (['f"""{filename} processed"""'], {}), "(f'{filename} processed')\n", (4648, 4673), False, 'import logging\n'), ((4963, 5033), 'logging.debug', 'logging.debug', (['f"""{df_sel.shape[0]} out of {df.shape[0]} rows selected"""'], {}), "(f'{df_sel.shape[0]} out of {df.shape[0]} rows selected')\n", (4976, 5033), False, 'import logging\n'), ((5166, 5204), 'logging.debug', 'logging.debug', (['f"""{filename} processed"""'], {}), "(f'{filename} processed')\n", (5179, 5204), False, 'import logging\n'), ((5535, 5605), 'logging.debug', 'logging.debug', (['f"""{df_sel.shape[0]} out of {df.shape[0]} rows selected"""'], {}), "(f'{df_sel.shape[0]} out of {df.shape[0]} rows selected')\n", (5548, 5605), False, 'import logging\n'), ((5738, 5776), 'logging.debug', 'logging.debug', (['f"""{filename} processed"""'], {}), "(f'{filename} processed')\n", (5751, 5776), False, 'import logging\n'), ((6741, 6787), 'logging.debug', 'logging.debug', (['f"""{prcp.shape[0]} station*days"""'], {}), "(f'{prcp.shape[0]} station*days')\n", (6754, 6787), False, 'import logging\n'), ((6871, 6920), 'logging.debug', 'logging.debug', (['f"""{station_ded.shape[0]} stations"""'], {}), "(f'{station_ded.shape[0]} stations')\n", (6884, 6920), False, 'import logging\n'), ((6993, 7051), 'datetime.date', 'date', (['data_end_dt.year', 'data_end_dt.month', 'data_end_dt.day'], {}), '(data_end_dt.year, data_end_dt.month, data_end_dt.day)\n', (6997, 7051), False, 'from datetime import timedelta, date, datetime\n'), ((7056, 7103), 'logging.debug', 'logging.debug', (['f"""data_end_date={data_end_date}"""'], {}), "(f'data_end_date={data_end_date}')\n", (7069, 7103), False, 'import logging\n'), ((7181, 7227), 'logging.debug', 'logging.debug', (['f"""{prcp.shape[0]} station*days"""'], {}), "(f'{prcp.shape[0]} station*days')\n", (7194, 7227), False, 'import logging\n'), ((7331, 7380), 'logging.debug', 'logging.debug', (['f"""{station_ded.shape[0]} stations"""'], {}), "(f'{station_ded.shape[0]} stations')\n", (7344, 7380), False, 'import logging\n'), ((7677, 7715), 'os.path.join', 'os.path.join', (['prcp_path', 'f"""{year}.csv"""'], {}), "(prcp_path, f'{year}.csv')\n", (7689, 7715), False, 'import os\n'), ((7720, 7756), 'logging.debug', 'logging.debug', (['f"""reading {filename}"""'], {}), "(f'reading {filename}')\n", (7733, 7756), False, 'import logging\n'), ((8035, 8082), 'logging.debug', 'logging.debug', (['f"""data_end_date={data_end_date}"""'], {}), "(f'data_end_date={data_end_date}')\n", (8048, 8082), False, 'import logging\n'), ((8087, 8173), 'logging.debug', 'logging.debug', (['f"""active_period_length_days={config[\'active_period_length_days\']}"""'], {}), '(\n f"active_period_length_days={config[\'active_period_length_days\']}")\n', (8100, 8173), False, 'import logging\n'), ((8267, 8322), 'logging.debug', 'logging.debug', (['f"""active_start_date={active_start_date}"""'], {}), "(f'active_start_date={active_start_date}')\n", (8280, 8322), False, 'import logging\n'), ((8832, 8882), 'logging.debug', 'logging.debug', (['f"""{num_files} files in {prcp_path}"""'], {}), "(f'{num_files} files in {prcp_path}')\n", (8845, 8882), False, 'import logging\n'), ((9746, 9782), 'logging.debug', 'logging.debug', (['"""transpose completed"""'], {}), "('transpose completed')\n", (9759, 9782), False, 'import logging\n'), ((10360, 10403), 'pandas.Series', 'pd.Series', (['calendar_values'], {'index': 'date_axis'}), '(calendar_values, index=date_axis)\n', (10369, 10403), True, 'import pandas as pd\n'), ((10408, 10582), 'logging.debug', 'logging.debug', (['f"""calendar with {num_days} days from {date_axis[-1]} to {date_axis[0]} with recent period of {num_days_recent} from {date_axis[num_days_recent - 1]}"""'], {}), "(\n f'calendar with {num_days} days from {date_axis[-1]} to {date_axis[0]} with recent period of {num_days_recent} from {date_axis[num_days_recent - 1]}'\n )\n", (10421, 10582), False, 'import logging\n'), ((16865, 16957), 'logging.info', 'logging.info', (['f"""{stations.shape[0]} active stations with data_end_date={data_end_date}"""'], {}), "(\n f'{stations.shape[0]} active stations with data_end_date={data_end_date}')\n", (16877, 16957), False, 'import logging\n'), ((18413, 18499), 'pandas.DataFrame', 'pd.DataFrame', (['cdf_list'], {'columns': "['country_code', 'continent_code', 'country_name']"}), "(cdf_list, columns=['country_code', 'continent_code',\n 'country_name'])\n", (18425, 18499), True, 'import pandas as pd\n'), ((19561, 19606), 'pandas.DataFrame', 'pd.DataFrame', (['stations_list'], {'columns': 'colnames'}), '(stations_list, columns=colnames)\n', (19573, 19606), True, 'import pandas as pd\n'), ((19869, 19898), 'pandas.read_csv', 'pd.read_csv', (['cc_file'], {'sep': '""","""'}), "(cc_file, sep=',')\n", (19880, 19898), True, 'import pandas as pd\n'), ((20681, 20726), 'logging.debug', 'logging.debug', (['f"""dateframe {df.shape} loaded"""'], {}), "(f'dateframe {df.shape} loaded')\n", (20694, 20726), False, 'import logging\n'), ((20847, 20899), 'logging.debug', 'logging.debug', (['f"""prcp data {df_sel.shape} extracted"""'], {}), "(f'prcp data {df_sel.shape} extracted')\n", (20860, 20899), False, 'import logging\n'), ((21318, 21375), 'logging.debug', 'logging.debug', (['f"""mirror data {df_mirror.shape} extracted"""'], {}), "(f'mirror data {df_mirror.shape} extracted')\n", (21331, 21375), False, 'import logging\n'), ((22339, 22373), 'logging.debug', 'logging.debug', (['"""extract completed"""'], {}), "('extract completed')\n", (22352, 22373), False, 'import logging\n'), ((22814, 22839), 'numpy.zeros', 'np.zeros', (['nst'], {'dtype': 'bool'}), '(nst, dtype=bool)\n', (22822, 22839), True, 'import numpy as np\n'), ((23738, 23752), 'numpy.argsort', 'np.argsort', (['x1'], {}), '(x1)\n', (23748, 23752), True, 'import numpy as np\n'), ((23770, 23784), 'numpy.argsort', 'np.argsort', (['x2'], {}), '(x2)\n', (23780, 23784), True, 'import numpy as np\n'), ((24598, 24655), 'pandas.DataFrame', 'pd.DataFrame', (['q'], {'columns': "['station', 'dateto', 'prcp_mm']"}), "(q, columns=['station', 'dateto', 'prcp_mm'])\n", (24610, 24655), True, 'import pandas as pd\n'), ((25015, 25035), 'datetime.date', 'date', (['(year - 2)', '(1)', '(1)'], {}), '(year - 2, 1, 1)\n', (25019, 25035), False, 'from datetime import timedelta, date, datetime\n'), ((25049, 25067), 'datetime.date', 'date', (['year', '(12)', '(31)'], {}), '(year, 12, 31)\n', (25053, 25067), False, 'from datetime import timedelta, date, datetime\n'), ((25084, 25110), 'datetime.datetime', 'datetime', (['(year - 1)', '(12)', '(31)'], {}), '(year - 1, 12, 31)\n', (25092, 25110), False, 'from datetime import timedelta, date, datetime\n'), ((25125, 25180), 'pandas.date_range', 'pd.date_range', ([], {'start': 'start_date', 'end': 'end_date', 'freq': '"""D"""'}), "(start=start_date, end=end_date, freq='D')\n", (25138, 25180), True, 'import pandas as pd\n'), ((25948, 25971), 'numpy.cumsum', 'np.cumsum', (['day_observed'], {}), '(day_observed)\n', (25957, 25971), True, 'import numpy as np\n'), ((26313, 26338), 'numpy.arange', 'np.arange', (['(1981)', '(2010 + 1)'], {}), '(1981, 2010 + 1)\n', (26322, 26338), True, 'import numpy as np\n'), ((26481, 26508), 'pandas.concat', 'pd.concat', (['ref_list'], {'axis': '(0)'}), '(ref_list, axis=0)\n', (26490, 26508), True, 'import pandas as pd\n'), ((26601, 26638), 'numpy.array', 'np.array', (['[0.0, 0.25, 0.5, 0.75, 1.0]'], {}), '([0.0, 0.25, 0.5, 0.75, 1.0])\n', (26609, 26638), True, 'import numpy as np\n'), ((31170, 31198), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(12, 12)'}), '(figsize=(12, 12))\n', (31180, 31198), True, 'import matplotlib.pyplot as plt\n'), ((32056, 32065), 'matplotlib.pyplot.gca', 'plt.gca', ([], {}), '()\n', (32063, 32065), True, 'import matplotlib.pyplot as plt\n'), ((32553, 32574), 'bokeh.models.ColumnDataSource', 'ColumnDataSource', (['rdf'], {}), '(rdf)\n', (32569, 32574), False, 'from bokeh.models import HoverTool, ColumnDataSource, VArea, Line, VBar\n'), ((32635, 32845), 'bokeh.plotting.figure', 'figure', ([], {'plot_width': '(800)', 'plot_height': '(800)', 'title': 'f"""{stlabel}: current drought index is {100 * curr_drought_rate:.0f}%"""', 'y_axis_label': '"""3rd year cumulative precipitation in mm"""', 'x_axis_type': '"""datetime"""'}), "(plot_width=800, plot_height=800, title=\n f'{stlabel}: current drought index is {100 * curr_drought_rate:.0f}%',\n y_axis_label='3rd year cumulative precipitation in mm', x_axis_type=\n 'datetime')\n", (32641, 32845), False, 'from bokeh.plotting import figure\n'), ((35145, 35172), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(16, 9)'}), '(figsize=(16, 9))\n', (35155, 35172), True, 'import matplotlib.pyplot as plt\n'), ((35612, 35621), 'matplotlib.pyplot.gca', 'plt.gca', ([], {}), '()\n', (35619, 35621), True, 'import matplotlib.pyplot as plt\n'), ((35958, 35986), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(12, 12)'}), '(figsize=(12, 12))\n', (35968, 35986), True, 'import matplotlib.pyplot as plt\n'), ((35996, 36005), 'matplotlib.pyplot.gca', 'plt.gca', ([], {}), '()\n', (36003, 36005), True, 'import matplotlib.pyplot as plt\n'), ((37104, 37262), 'bokeh.plotting.figure', 'figure', ([], {'plot_width': '(800)', 'plot_height': '(800)', 'title': 'f"""Yearly precipitation totals, mean={prcp_pred_mean:.0f}mm"""', 'y_axis_label': '"""annual precipitation in mm"""'}), "(plot_width=800, plot_height=800, title=\n f'Yearly precipitation totals, mean={prcp_pred_mean:.0f}mm',\n y_axis_label='annual precipitation in mm')\n", (37110, 37262), False, 'from bokeh.plotting import figure\n'), ((39612, 39664), 'sqlalchemy.create_engine', 'create_engine', (['"""postgres://postgres:@localhost/ghcn"""'], {}), "('postgres://postgres:@localhost/ghcn')\n", (39625, 39664), False, 'from sqlalchemy import create_engine\n'), ((40678, 40736), 'datetime.date', 'date', (['data_end_dt.year', 'data_end_dt.month', 'data_end_dt.day'], {}), '(data_end_dt.year, data_end_dt.month, data_end_dt.day)\n', (40682, 40736), False, 'from datetime import timedelta, date, datetime\n'), ((40741, 40788), 'logging.debug', 'logging.debug', (['f"""data_end_date={data_end_date}"""'], {}), "(f'data_end_date={data_end_date}')\n", (40754, 40788), False, 'import logging\n'), ((41308, 41355), 'logging.debug', 'logging.debug', (['f"""cump_end_date={data_end_date}"""'], {}), "(f'cump_end_date={data_end_date}')\n", (41321, 41355), False, 'import logging\n'), ((41633, 41657), 'logging.debug', 'logging.debug', (['sql_query'], {}), '(sql_query)\n', (41646, 41657), False, 'import logging\n'), ((44753, 44779), 'logging.debug', 'logging.debug', (['"""completed"""'], {}), "('completed')\n", (44766, 44779), False, 'import logging\n'), ((46576, 46639), 'pandas.concat', 'pd.concat', (['[station_name, country_name, continent_name]'], {'axis': '(0)'}), '([station_name, country_name, continent_name], axis=0)\n', (46585, 46639), True, 'import pandas as pd\n'), ((46688, 46733), 'numpy.concatenate', 'np.concatenate', (['(stidx, stidx, stidx)'], {'axis': '(0)'}), '((stidx, stidx, stidx), axis=0)\n', (46702, 46733), True, 'import numpy as np\n'), ((46753, 46811), 'pandas.DataFrame', 'pd.DataFrame', (["{'node_name': node_name, 'station': station}"], {}), "({'node_name': node_name, 'station': station})\n", (46765, 46811), True, 'import pandas as pd\n'), ((46897, 46963), 'pandas.DataFrame', 'pd.DataFrame', (["{'node_name': nvc.index, 'num_stations': nvc.values}"], {}), "({'node_name': nvc.index, 'num_stations': nvc.values})\n", (46909, 46963), True, 'import pandas as pd\n'), ((47246, 47283), 'logging.debug', 'logging.debug', (['f"""max_year={max_year}"""'], {}), "(f'max_year={max_year}')\n", (47259, 47283), False, 'import logging\n'), ((47426, 47473), 'logging.debug', 'logging.debug', (['f"""max_day_index={max_day_index}"""'], {}), "(f'max_day_index={max_day_index}')\n", (47439, 47473), False, 'import logging\n'), ((47788, 47819), 'logging.debug', 'logging.debug', (['sql_last_cumprcp'], {}), '(sql_last_cumprcp)\n', (47801, 47819), False, 'import logging\n'), ((47963, 48014), 'logging.debug', 'logging.debug', (['f"""last_cumprcp={last_cumprcp.shape}"""'], {}), "(f'last_cumprcp={last_cumprcp.shape}')\n", (47976, 48014), False, 'import logging\n'), ((48393, 48426), 'logging.debug', 'logging.debug', (['sql_last_reference'], {}), '(sql_last_reference)\n', (48406, 48426), False, 'import logging\n'), ((48576, 48631), 'logging.debug', 'logging.debug', (['f"""last_reference={last_reference.shape}"""'], {}), "(f'last_reference={last_reference.shape}')\n", (48589, 48631), False, 'import logging\n'), ((48697, 48738), 'logging.debug', 'logging.debug', (['f"""drought={drought.shape}"""'], {}), "(f'drought={drought.shape}')\n", (48710, 48738), False, 'import logging\n'), ((49013, 49052), 'logging.debug', 'logging.debug', (['f"""out_df={out_df.shape}"""'], {}), "(f'out_df={out_df.shape}')\n", (49026, 49052), False, 'import logging\n'), ((49555, 49571), 'numpy.sum', 'np.sum', (['flag_dry'], {}), '(flag_dry)\n', (49561, 49571), True, 'import numpy as np\n'), ((49993, 50029), 'numpy.ceil', 'np.ceil', (['(num_stations / agg_stations)'], {}), '(num_stations / agg_stations)\n', (50000, 50029), True, 'import numpy as np\n'), ((50558, 50610), 'numpy.array', 'np.array', (["['blue', 'cyan', 'green', 'orange', 'red']"], {}), "(['blue', 'cyan', 'green', 'orange', 'red'])\n", (50566, 50610), True, 'import numpy as np\n'), ((50636, 50724), 'pandas.cut', 'pd.cut', (['drought.drought_index', '[-1.0, -0.99, -0.5, +0.5, +0.99, +1.001]'], {'right': '(False)'}), '(drought.drought_index, [-1.0, -0.99, -0.5, +0.5, +0.99, +1.001],\n right=False)\n', (50642, 50724), True, 'import pandas as pd\n'), ((51116, 51141), 'bokeh.models.ColumnDataSource', 'ColumnDataSource', (['drought'], {}), '(drought)\n', (51132, 51141), False, 'from bokeh.models import HoverTool, ColumnDataSource, VArea, Line, VBar\n'), ((51150, 51353), 'bokeh.plotting.figure', 'figure', ([], {'plot_width': '(1600)', 'plot_height': '(600)', 'title': 'f"""Drought rate is {100 * drought_rate:.0f}%={num_dry}/{num_stations}."""', 'y_axis_label': '"""Drought Index"""', 'x_axis_label': '"""Station Rank by Drought Index"""'}), "(plot_width=1600, plot_height=600, title=\n f'Drought rate is {100 * drought_rate:.0f}%={num_dry}/{num_stations}.',\n y_axis_label='Drought Index', x_axis_label='Station Rank by Drought Index')\n", (51156, 51353), False, 'from bokeh.plotting import figure\n'), ((52825, 52862), 'logging.debug', 'logging.debug', (['f"""current_year={year}"""'], {}), "(f'current_year={year}')\n", (52838, 52862), False, 'import logging\n'), ((53108, 53129), 'pandas.read_csv', 'pd.read_csv', (['out_file'], {}), '(out_file)\n', (53119, 53129), True, 'import pandas as pd\n'), ((54652, 54680), 'bokeh.tile_providers.get_provider', 'get_provider', (['STAMEN_TERRAIN'], {}), '(STAMEN_TERRAIN)\n', (54664, 54680), False, 'from bokeh.tile_providers import get_provider, STAMEN_TERRAIN\n'), ((54770, 54791), 'bokeh.models.ColumnDataSource', 'ColumnDataSource', (['dfm'], {}), '(dfm)\n', (54786, 54791), False, 'from bokeh.models import HoverTool, ColumnDataSource, VArea, Line, VBar\n'), ((54800, 54924), 'bokeh.plotting.figure', 'figure', ([], {'plot_width': '(1600)', 'plot_height': '(800)', 'x_range': 'xrange', 'y_range': 'yrange', 'x_axis_type': '"""mercator"""', 'y_axis_type': '"""mercator"""'}), "(plot_width=1600, plot_height=800, x_range=xrange, y_range=yrange,\n x_axis_type='mercator', y_axis_type='mercator')\n", (54806, 54924), False, 'from bokeh.plotting import figure\n'), ((55379, 55402), 'bokeh.models.HoverTool', 'HoverTool', ([], {'tooltips': 'ttp'}), '(tooltips=ttp)\n', (55388, 55402), False, 'from bokeh.models import HoverTool, ColumnDataSource, VArea, Line, VBar\n'), ((2077, 2144), 'numpy.interp', 'np.interp', (['x'], {'xp': 'self.x_values', 'fp': 'self.cdf_values', 'left': '(0)', 'right': '(1)'}), '(x, xp=self.x_values, fp=self.cdf_values, left=0, right=1)\n', (2086, 2144), True, 'import numpy as np\n'), ((2299, 2401), 'numpy.interp', 'np.interp', (['q'], {'xp': 'self.cdf_values', 'fp': 'self.x_values', 'left': 'self.x_values[0]', 'right': 'self.x_values[-1]'}), '(q, xp=self.cdf_values, fp=self.x_values, left=self.x_values[0],\n right=self.x_values[-1])\n', (2308, 2401), True, 'import numpy as np\n'), ((3557, 3583), 'gzip.open', 'gzip.open', (['read_path', '"""rb"""'], {}), "(read_path, 'rb')\n", (3566, 3583), False, 'import gzip\n'), ((3603, 3749), 'pandas.read_csv', 'pd.read_csv', (['f'], {'header': 'None', 'names': "['station', 'dateto', 'element', 'value', 'm_flag', 'q_flag', 's_flag',\n 'obs_time']", 'parse_dates': "['dateto']"}), "(f, header=None, names=['station', 'dateto', 'element', 'value',\n 'm_flag', 'q_flag', 's_flag', 'obs_time'], parse_dates=['dateto'])\n", (3614, 3749), True, 'import pandas as pd\n'), ((3938, 3958), 'yaml.safe_load', 'yaml.safe_load', (['file'], {}), '(file)\n', (3952, 3958), False, 'import yaml\n'), ((4368, 4427), 'dfply.transmute', 'transmute', ([], {'station': 'X.station', 'dateto': 'X.dateto', 'prcp': 'X.value'}), '(station=X.station, dateto=X.dateto, prcp=X.value)\n', (4377, 4427), False, 'from dfply import X, group_by, summarize, mask, n, transmute, select, left_join, ungroup, arrange, mutate\n'), ((4562, 4607), 'os.path.join', 'os.path.join', (['prcp_path', 'f"""{year_string}.csv"""'], {}), "(prcp_path, f'{year_string}.csv')\n", (4574, 4607), False, 'import os\n'), ((4899, 4958), 'dfply.transmute', 'transmute', ([], {'station': 'X.station', 'dateto': 'X.dateto', 'prcp': 'X.value'}), '(station=X.station, dateto=X.dateto, prcp=X.value)\n', (4908, 4958), False, 'from dfply import X, group_by, summarize, mask, n, transmute, select, left_join, ungroup, arrange, mutate\n'), ((5093, 5138), 'os.path.join', 'os.path.join', (['prcp_path', 'f"""{year_string}.csv"""'], {}), "(prcp_path, f'{year_string}.csv')\n", (5105, 5138), False, 'import os\n'), ((5471, 5530), 'dfply.transmute', 'transmute', ([], {'station': 'X.station', 'dateto': 'X.dateto', 'prcp': 'X.value'}), '(station=X.station, dateto=X.dateto, prcp=X.value)\n', (5480, 5530), False, 'from dfply import X, group_by, summarize, mask, n, transmute, select, left_join, ungroup, arrange, mutate\n'), ((5665, 5710), 'os.path.join', 'os.path.join', (['prcp_path', 'f"""{year_string}.csv"""'], {}), "(prcp_path, f'{year_string}.csv')\n", (5677, 5710), False, 'import os\n'), ((5847, 5871), 'os.path.isdir', 'os.path.isdir', (['prcp_path'], {}), '(prcp_path)\n', (5860, 5871), False, 'import os\n'), ((5881, 5903), 'os.makedirs', 'os.makedirs', (['prcp_path'], {}), '(prcp_path)\n', (5892, 5903), False, 'import os\n'), ((5931, 5955), 'os.listdir', 'os.listdir', (['by_year_path'], {}), '(by_year_path)\n', (5941, 5955), False, 'import os\n'), ((6137, 6161), 'os.path.isdir', 'os.path.isdir', (['prcp_path'], {}), '(prcp_path)\n', (6150, 6161), False, 'import os\n'), ((6171, 6193), 'os.makedirs', 'os.makedirs', (['prcp_path'], {}), '(prcp_path)\n', (6182, 6193), False, 'import os\n'), ((6221, 6245), 'os.listdir', 'os.listdir', (['by_year_path'], {}), '(by_year_path)\n', (6231, 6245), False, 'import os\n'), ((6466, 6490), 'os.path.isdir', 'os.path.isdir', (['prcp_path'], {}), '(prcp_path)\n', (6479, 6490), False, 'import os\n'), ((6500, 6522), 'os.makedirs', 'os.makedirs', (['prcp_path'], {}), '(prcp_path)\n', (6511, 6522), False, 'import os\n'), ((6550, 6574), 'os.listdir', 'os.listdir', (['by_year_path'], {}), '(by_year_path)\n', (6560, 6574), False, 'import os\n'), ((7768, 7813), 'pandas.read_csv', 'pd.read_csv', (['filename'], {'parse_dates': "['dateto']"}), "(filename, parse_dates=['dateto'])\n", (7779, 7813), True, 'import pandas as pd\n'), ((7817, 7845), 'dfply.arrange', 'arrange', (['X.dateto', 'X.station'], {}), '(X.dateto, X.station)\n', (7824, 7845), False, 'from dfply import X, group_by, summarize, mask, n, transmute, select, left_join, ungroup, arrange, mutate\n'), ((7966, 7994), 'dfply.mask', 'mask', (['(X.dateto <= date_valid)'], {}), '(X.dateto <= date_valid)\n', (7970, 7994), False, 'from dfply import X, group_by, summarize, mask, n, transmute, select, left_join, ungroup, arrange, mutate\n'), ((8209, 8264), 'datetime.timedelta', 'timedelta', ([], {'days': "(config['active_period_length_days'] - 1)"}), "(days=config['active_period_length_days'] - 1)\n", (8218, 8264), False, 'from datetime import timedelta, date, datetime\n'), ((8355, 8390), 'dfply.mask', 'mask', (['(X.dateto >= active_start_date)'], {}), '(X.dateto >= active_start_date)\n', (8359, 8390), False, 'from dfply import X, group_by, summarize, mask, n, transmute, select, left_join, ungroup, arrange, mutate\n'), ((8489, 8507), 'dfply.arrange', 'arrange', (['X.station'], {}), '(X.station)\n', (8496, 8507), False, 'from dfply import X, group_by, summarize, mask, n, transmute, select, left_join, ungroup, arrange, mutate\n'), ((8634, 8643), 'dfply.ungroup', 'ungroup', ([], {}), '()\n', (8641, 8643), False, 'from dfply import X, group_by, summarize, mask, n, transmute, select, left_join, ungroup, arrange, mutate\n'), ((8760, 8781), 'os.listdir', 'os.listdir', (['prcp_path'], {}), '(prcp_path)\n', (8770, 8781), False, 'import os\n'), ((9104, 9159), 'logging.debug', 'logging.debug', (['f"""{num_stations} stations in {filename}"""'], {}), "(f'{num_stations} stations in {filename}')\n", (9117, 9159), False, 'import logging\n'), ((9703, 9741), 'logging.debug', 'logging.debug', (['f"""{filename} processed"""'], {}), "(f'{filename} processed')\n", (9716, 9741), False, 'import logging\n'), ((10141, 10201), 'pandas.date_range', 'pd.date_range', ([], {'end': 'data_end_date', 'periods': 'num_days', 'freq': '"""D"""'}), "(end=data_end_date, periods=num_days, freq='D')\n", (10154, 10201), True, 'import pandas as pd\n'), ((11591, 11635), 'logging.debug', 'logging.debug', (['f"""date_limits: {d1} and {d2}"""'], {}), "(f'date_limits: {d1} and {d2}')\n", (11604, 11635), False, 'import logging\n'), ((11662, 11712), 'pandas.DataFrame', 'pd.DataFrame', (["{'dateto': calendar[calendar].index}"], {}), "({'dateto': calendar[calendar].index})\n", (11674, 11712), True, 'import pandas as pd\n'), ((11849, 11900), 'pandas.DataFrame', 'pd.DataFrame', (["{'dateto': calendar[~calendar].index}"], {}), "({'dateto': calendar[~calendar].index})\n", (11861, 11900), True, 'import pandas as pd\n'), ((12189, 12244), 'logging.debug', 'logging.debug', (['f"""recent_delta_days={recent_delta_days}"""'], {}), "(f'recent_delta_days={recent_delta_days}')\n", (12202, 12244), False, 'import logging\n'), ((12435, 12496), 'logging.debug', 'logging.debug', (['f"""preceding_delta_days={preceding_delta_days}"""'], {}), "(f'preceding_delta_days={preceding_delta_days}')\n", (12448, 12496), False, 'import logging\n'), ((16274, 16310), 'logging.debug', 'logging.debug', (['"""df_running is empty"""'], {}), "('df_running is empty')\n", (16287, 16310), False, 'import logging\n'), ((16375, 16387), 'datetime.date.today', 'date.today', ([], {}), '()\n', (16385, 16387), False, 'from datetime import timedelta, date, datetime\n'), ((17269, 17297), 'logging.info', 'logging.info', (['f"""year={year}"""'], {}), "(f'year={year}')\n", (17281, 17297), False, 'import logging\n'), ((20775, 20842), 'dfply.transmute', 'transmute', ([], {'station': 'X.station', 'dateto': 'X.dateto', 'prcp_mm': '(X.value / 10)'}), '(station=X.station, dateto=X.dateto, prcp_mm=X.value / 10)\n', (20784, 20842), False, 'from dfply import X, group_by, summarize, mask, n, transmute, select, left_join, ungroup, arrange, mutate\n'), ((21772, 21828), 'logging.debug', 'logging.debug', (['f"""sql insert to {table_name} in progress"""'], {}), "(f'sql insert to {table_name} in progress')\n", (21785, 21828), False, 'import logging\n'), ((21915, 21965), 'logging.debug', 'logging.debug', (['f"""insert to {table_name} completed"""'], {}), "(f'insert to {table_name} completed')\n", (21928, 21965), False, 'import logging\n'), ((21984, 22019), 'logging.debug', 'logging.debug', (['"""increment is empty"""'], {}), "('increment is empty')\n", (21997, 22019), False, 'import logging\n'), ((22114, 22138), 'os.listdir', 'os.listdir', (['by_year_path'], {}), '(by_year_path)\n', (22124, 22138), False, 'import os\n'), ((22213, 22258), 'logging.debug', 'logging.debug', (['f"""{i + 1}/{nfiles} {filename}"""'], {}), "(f'{i + 1}/{nfiles} {filename}')\n", (22226, 22258), False, 'import logging\n'), ((23236, 23251), 'numpy.sum', 'np.sum', (['inperim'], {}), '(inperim)\n', (23242, 23251), True, 'import numpy as np\n'), ((23408, 23427), 'numpy.argsort', 'np.argsort', (['distvec'], {}), '(distvec)\n', (23418, 23427), True, 'import numpy as np\n'), ((24299, 24314), 'json.load', 'json.load', (['file'], {}), '(file)\n', (24308, 24314), False, 'import json\n'), ((24435, 24489), 'sqlalchemy.create_engine', 'create_engine', (['"""postgresql://postgres:@localhost/ghcn"""'], {}), "('postgresql://postgres:@localhost/ghcn')\n", (24448, 24489), False, 'from sqlalchemy import create_engine\n'), ((29046, 29064), 'numpy.array', 'np.array', (['cum_prcp'], {}), '(cum_prcp)\n', (29054, 29064), True, 'import numpy as np\n'), ((30782, 30799), 'numpy.ceil', 'np.ceil', (['(y / step)'], {}), '(y / step)\n', (30789, 30799), True, 'import numpy as np\n'), ((31350, 31441), 'matplotlib.pyplot.fill_between', 'plt.fill_between', ([], {'x': 'xx', 'y1': '(0)', 'y2': "rdf['prcp_min']", 'color': '"""red"""', 'linewidth': '(0.0)', 'alpha': '(0.5)'}), "(x=xx, y1=0, y2=rdf['prcp_min'], color='red', linewidth=0.0,\n alpha=0.5)\n", (31366, 31441), True, 'import matplotlib.pyplot as plt\n'), ((31446, 31555), 'matplotlib.pyplot.fill_between', 'plt.fill_between', ([], {'x': 'xx', 'y1': "rdf['prcp_min']", 'y2': "rdf['prcp_p25']", 'color': '"""orange"""', 'linewidth': '(0.0)', 'alpha': '(0.5)'}), "(x=xx, y1=rdf['prcp_min'], y2=rdf['prcp_p25'], color=\n 'orange', linewidth=0.0, alpha=0.5)\n", (31462, 31555), True, 'import matplotlib.pyplot as plt\n'), ((31559, 31667), 'matplotlib.pyplot.fill_between', 'plt.fill_between', ([], {'x': 'xx', 'y1': "rdf['prcp_p25']", 'y2': "rdf['prcp_p75']", 'color': '"""green"""', 'linewidth': '(0.0)', 'alpha': '(0.5)'}), "(x=xx, y1=rdf['prcp_p25'], y2=rdf['prcp_p75'], color=\n 'green', linewidth=0.0, alpha=0.5)\n", (31575, 31667), True, 'import matplotlib.pyplot as plt\n'), ((31671, 31777), 'matplotlib.pyplot.fill_between', 'plt.fill_between', ([], {'x': 'xx', 'y1': "rdf['prcp_p75']", 'y2': "rdf['prcp_max']", 'color': '"""cyan"""', 'linewidth': '(0.0)', 'alpha': '(0.5)'}), "(x=xx, y1=rdf['prcp_p75'], y2=rdf['prcp_max'], color='cyan',\n linewidth=0.0, alpha=0.5)\n", (31687, 31777), True, 'import matplotlib.pyplot as plt\n'), ((31782, 31880), 'matplotlib.pyplot.fill_between', 'plt.fill_between', ([], {'x': 'xx', 'y1': "rdf['prcp_max']", 'y2': 'prcp_ub', 'color': '"""blue"""', 'linewidth': '(0.0)', 'alpha': '(0.5)'}), "(x=xx, y1=rdf['prcp_max'], y2=prcp_ub, color='blue',\n linewidth=0.0, alpha=0.5)\n", (31798, 31880), True, 'import matplotlib.pyplot as plt\n'), ((31885, 31924), 'matplotlib.pyplot.plot', 'plt.plot', (['xx', "rdf['prcp_p50']"], {'c': '"""grey"""'}), "(xx, rdf['prcp_p50'], c='grey')\n", (31893, 31924), True, 'import matplotlib.pyplot as plt\n'), ((33010, 33082), 'bokeh.models.VArea', 'VArea', ([], {'x': '"""dateto"""', 'y1': '(0)', 'y2': '"""prcp_min"""', 'fill_color': '"""red"""', 'fill_alpha': '(0.5)'}), "(x='dateto', y1=0, y2='prcp_min', fill_color='red', fill_alpha=0.5)\n", (33015, 33082), False, 'from bokeh.models import HoverTool, ColumnDataSource, VArea, Line, VBar\n'), ((33098, 33186), 'bokeh.models.VArea', 'VArea', ([], {'x': '"""dateto"""', 'y1': '"""prcp_min"""', 'y2': '"""prcp_p25"""', 'fill_color': '"""orange"""', 'fill_alpha': '(0.5)'}), "(x='dateto', y1='prcp_min', y2='prcp_p25', fill_color='orange',\n fill_alpha=0.5)\n", (33103, 33186), False, 'from bokeh.models import HoverTool, ColumnDataSource, VArea, Line, VBar\n'), ((33198, 33285), 'bokeh.models.VArea', 'VArea', ([], {'x': '"""dateto"""', 'y1': '"""prcp_p25"""', 'y2': '"""prcp_p75"""', 'fill_color': '"""green"""', 'fill_alpha': '(0.5)'}), "(x='dateto', y1='prcp_p25', y2='prcp_p75', fill_color='green',\n fill_alpha=0.5)\n", (33203, 33285), False, 'from bokeh.models import HoverTool, ColumnDataSource, VArea, Line, VBar\n'), ((33297, 33383), 'bokeh.models.VArea', 'VArea', ([], {'x': '"""dateto"""', 'y1': '"""prcp_p75"""', 'y2': '"""prcp_max"""', 'fill_color': '"""cyan"""', 'fill_alpha': '(0.5)'}), "(x='dateto', y1='prcp_p75', y2='prcp_max', fill_color='cyan',\n fill_alpha=0.5)\n", (33302, 33383), False, 'from bokeh.models import HoverTool, ColumnDataSource, VArea, Line, VBar\n'), ((33395, 33474), 'bokeh.models.VArea', 'VArea', ([], {'x': '"""dateto"""', 'y1': '"""prcp_max"""', 'y2': 'prcp_ub', 'fill_color': '"""blue"""', 'fill_alpha': '(0.5)'}), "(x='dateto', y1='prcp_max', y2=prcp_ub, fill_color='blue', fill_alpha=0.5)\n", (33400, 33474), False, 'from bokeh.models import HoverTool, ColumnDataSource, VArea, Line, VBar\n'), ((33490, 33553), 'bokeh.models.Line', 'Line', ([], {'x': '"""dateto"""', 'y': '"""prcp_p50"""', 'line_color': '"""grey"""', 'line_width': '(3)'}), "(x='dateto', y='prcp_p50', line_color='grey', line_width=3)\n", (33494, 33553), False, 'from bokeh.models import HoverTool, ColumnDataSource, VArea, Line, VBar\n'), ((34159, 34244), 'bokeh.models.HoverTool', 'HoverTool', ([], {'renderers': '[rref]', 'tooltips': 'ttp_ref', 'formatters': "{'@dateto': 'datetime'}"}), "(renderers=[rref], tooltips=ttp_ref, formatters={'@dateto':\n 'datetime'})\n", (34168, 34244), False, 'from bokeh.models import HoverTool, ColumnDataSource, VArea, Line, VBar\n'), ((34311, 34373), 'bokeh.models.Line', 'Line', ([], {'x': '"""dateto"""', 'y': '"""ytd_prcp"""', 'line_color': '"""red"""', 'line_width': '(3)'}), "(x='dateto', y='ytd_prcp', line_color='red', line_width=3)\n", (34315, 34373), False, 'from bokeh.models import HoverTool, ColumnDataSource, VArea, Line, VBar\n'), ((34841, 34926), 'bokeh.models.HoverTool', 'HoverTool', ([], {'renderers': '[rcur]', 'tooltips': 'ttp_cur', 'formatters': "{'@dateto': 'datetime'}"}), "(renderers=[rcur], tooltips=ttp_cur, formatters={'@dateto':\n 'datetime'})\n", (34850, 34926), False, 'from bokeh.models import HoverTool, ColumnDataSource, VArea, Line, VBar\n'), ((35329, 35434), 'matplotlib.pyplot.fill_between', 'plt.fill_between', (["rdf['dateto']"], {'y1': "rdf['fill_min']", 'y2': "rdf['fill_max']", 'color': '"""lightgray"""', 'alpha': '(0.5)'}), "(rdf['dateto'], y1=rdf['fill_min'], y2=rdf['fill_max'],\n color='lightgray', alpha=0.5)\n", (35345, 35434), True, 'import matplotlib.pyplot as plt\n'), ((35439, 35543), 'matplotlib.pyplot.fill_between', 'plt.fill_between', (["rdf['dateto']"], {'y1': "rdf['fill_p25']", 'y2': "rdf['fill_p75']", 'color': '"""darkgray"""', 'alpha': '(0.5)'}), "(rdf['dateto'], y1=rdf['fill_p25'], y2=rdf['fill_p75'],\n color='darkgray', alpha=0.5)\n", (35455, 35543), True, 'import matplotlib.pyplot as plt\n'), ((35548, 35602), 'matplotlib.pyplot.plot', 'plt.plot', (["rdf['dateto']", "rdf['fill_p50']"], {'color': '"""gray"""'}), "(rdf['dateto'], rdf['fill_p50'], color='gray')\n", (35556, 35602), True, 'import matplotlib.pyplot as plt\n'), ((36244, 36254), 'numpy.min', 'np.min', (['xx'], {}), '(xx)\n', (36250, 36254), True, 'import numpy as np\n'), ((36268, 36278), 'numpy.max', 'np.max', (['xx'], {}), '(xx)\n', (36274, 36278), True, 'import numpy as np\n'), ((36292, 36303), 'numpy.mean', 'np.mean', (['xx'], {}), '(xx)\n', (36299, 36303), True, 'import numpy as np\n'), ((36317, 36328), 'numpy.mean', 'np.mean', (['yy'], {}), '(yy)\n', (36324, 36328), True, 'import numpy as np\n'), ((36337, 36363), 'matplotlib.pyplot.bar', 'plt.bar', (['xx', 'yy'], {'width': '(0.8)'}), '(xx, yy, width=0.8)\n', (36344, 36363), True, 'import matplotlib.pyplot as plt\n'), ((36372, 36397), 'matplotlib.pyplot.step', 'plt.step', (['xx', 'dd'], {'c': '"""red"""'}), "(xx, dd, c='red')\n", (36380, 36397), True, 'import matplotlib.pyplot as plt\n'), ((36406, 36448), 'matplotlib.pyplot.plot', 'plt.plot', (['[x1, x2]', '[my, my]'], {'color': '"""blue"""'}), "([x1, x2], [my, my], color='blue')\n", (36414, 36448), True, 'import matplotlib.pyplot as plt\n'), ((37329, 37350), 'bokeh.models.ColumnDataSource', 'ColumnDataSource', (['dfy'], {}), '(dfy)\n', (37345, 37350), False, 'from bokeh.models import HoverTool, ColumnDataSource, VArea, Line, VBar\n'), ((37366, 37444), 'bokeh.models.VBar', 'VBar', ([], {'x': '"""year"""', 'top': '"""prcp_mm"""', 'fill_color': '"""blue"""', 'line_color': '"""blue"""', 'width': '(0.8)'}), "(x='year', top='prcp_mm', fill_color='blue', line_color='blue', width=0.8)\n", (37370, 37444), False, 'from bokeh.models import HoverTool, ColumnDataSource, VArea, Line, VBar\n'), ((37460, 37567), 'bokeh.models.VBar', 'VBar', ([], {'x': '"""year"""', 'bottom': '"""prcp_mm"""', 'top': '"""prcp_pred"""', 'fill_color': '"""lightblue"""', 'line_color': '"""blue"""', 'width': '(0.8)'}), "(x='year', bottom='prcp_mm', top='prcp_pred', fill_color='lightblue',\n line_color='blue', width=0.8)\n", (37464, 37567), False, 'from bokeh.models import HoverTool, ColumnDataSource, VArea, Line, VBar\n'), ((37579, 37650), 'bokeh.models.Line', 'Line', ([], {'x': '"""year"""', 'y': '"""prcp_pred_mean"""', 'line_color': '"""darkblue"""', 'line_width': '(3)'}), "(x='year', y='prcp_pred_mean', line_color='darkblue', line_width=3)\n", (37583, 37650), False, 'from bokeh.models import HoverTool, ColumnDataSource, VArea, Line, VBar\n'), ((38095, 38118), 'bokeh.models.HoverTool', 'HoverTool', ([], {'tooltips': 'ttp'}), '(tooltips=ttp)\n', (38104, 38118), False, 'from bokeh.models import HoverTool, ColumnDataSource, VArea, Line, VBar\n'), ((39357, 39371), 'pandas.DataFrame', 'pd.DataFrame', ([], {}), '()\n', (39369, 39371), True, 'import pandas as pd\n'), ((39388, 39402), 'pandas.DataFrame', 'pd.DataFrame', ([], {}), '()\n', (39400, 39402), True, 'import pandas as pd\n'), ((41245, 41303), 'datetime.date', 'date', (['data_end_dt.year', 'data_end_dt.month', 'data_end_dt.day'], {}), '(data_end_dt.year, data_end_dt.month, data_end_dt.day)\n', (41249, 41303), False, 'from datetime import timedelta, date, datetime\n'), ((43690, 43712), 'logging.debug', 'logging.debug', (['dateto0'], {}), '(dateto0)\n', (43703, 43712), False, 'import logging\n'), ((44584, 44600), 'logging.debug', 'logging.debug', (['x'], {}), '(x)\n', (44597, 44600), False, 'import logging\n'), ((45744, 45782), 'logging.debug', 'logging.debug', (['"""tree nodes are unique"""'], {}), "('tree nodes are unique')\n", (45757, 45782), False, 'import logging\n'), ((45801, 45843), 'logging.error', 'logging.error', (['"""tree nodes are not unique"""'], {}), "('tree nodes are not unique')\n", (45814, 45843), False, 'import logging\n'), ((45902, 45918), 'numpy.sum', 'np.sum', (['(freq > 1)'], {}), '(freq > 1)\n', (45908, 45918), True, 'import numpy as np\n'), ((45927, 45968), 'logging.debug', 'logging.debug', (['f"""{ndup} duplicated names"""'], {}), "(f'{ndup} duplicated names')\n", (45940, 45968), False, 'import logging\n'), ((48941, 49008), 'dfply.select', 'select', (['X.station', 'X.drought_index', 'X.cum_prcp_pred', 'X.cum_fillrate'], {}), '(X.station, X.drought_index, X.cum_prcp_pred, X.cum_fillrate)\n', (48947, 49008), False, 'from dfply import X, group_by, summarize, mask, n, transmute, select, left_join, ungroup, arrange, mutate\n'), ((51653, 51681), 'bokeh.models.HoverTool', 'HoverTool', ([], {'tooltips': 'tooltips'}), '(tooltips=tooltips)\n', (51662, 51681), False, 'from bokeh.models import HoverTool, ColumnDataSource, VArea, Line, VBar\n'), ((53026, 53043), 'dfply.mutate', 'mutate', ([], {'year': 'year'}), '(year=year)\n', (53032, 53043), False, 'from dfply import X, group_by, summarize, mask, n, transmute, select, left_join, ungroup, arrange, mutate\n'), ((53209, 53228), 'dfply.mask', 'mask', (['(X.year < year)'], {}), '(X.year < year)\n', (53213, 53228), False, 'from dfply import X, group_by, summarize, mask, n, transmute, select, left_join, ungroup, arrange, mutate\n'), ((53930, 53945), 'numpy.radians', 'np.radians', (['lon'], {}), '(lon)\n', (53940, 53945), True, 'import numpy as np\n'), ((1118, 1151), 'numpy.unique', 'np.unique', (['xv'], {'return_counts': '(True)'}), '(xv, return_counts=True)\n', (1127, 1151), True, 'import numpy as np\n'), ((1177, 1195), 'numpy.argsort', 'np.argsort', (['values'], {}), '(values)\n', (1187, 1195), True, 'import numpy as np\n'), ((1539, 1553), 'numpy.argsort', 'np.argsort', (['xv'], {}), '(xv)\n', (1549, 1553), True, 'import numpy as np\n'), ((1788, 1844), 'numpy.unique', 'np.unique', (['values'], {'return_index': '(True)', 'return_counts': '(True)'}), '(values, return_index=True, return_counts=True)\n', (1797, 1844), True, 'import numpy as np\n'), ((2219, 2233), 'numpy.all', 'np.all', (['(q >= 0)'], {}), '(q >= 0)\n', (2225, 2233), True, 'import numpy as np\n'), ((2238, 2252), 'numpy.all', 'np.all', (['(q <= 1)'], {}), '(q <= 1)\n', (2244, 2252), True, 'import numpy as np\n'), ((4339, 4364), 'dfply.mask', 'mask', (["(X.element == 'PRCP')"], {}), "(X.element == 'PRCP')\n", (4343, 4364), False, 'from dfply import X, group_by, summarize, mask, n, transmute, select, left_join, ungroup, arrange, mutate\n'), ((4859, 4885), 'dfply.mask', 'mask', (['(X.station == station)'], {}), '(X.station == station)\n', (4863, 4885), False, 'from dfply import X, group_by, summarize, mask, n, transmute, select, left_join, ungroup, arrange, mutate\n'), ((6814, 6833), 'dfply.group_by', 'group_by', (['X.station'], {}), '(X.station)\n', (6822, 6833), False, 'from dfply import X, group_by, summarize, mask, n, transmute, select, left_join, ungroup, arrange, mutate\n'), ((7254, 7273), 'dfply.group_by', 'group_by', (['X.station'], {}), '(X.station)\n', (7262, 7273), False, 'from dfply import X, group_by, summarize, mask, n, transmute, select, left_join, ungroup, arrange, mutate\n'), ((9324, 9369), 'os.path.join', 'os.path.join', (['stations_path', 'f"""{station}.csv"""'], {}), "(stations_path, f'{station}.csv')\n", (9336, 9369), False, 'import os\n'), ((9385, 9413), 'os.path.isfile', 'os.path.isfile', (['out_filename'], {}), '(out_filename)\n', (9399, 9413), False, 'import os\n'), ((9606, 9699), 'logging.debug', 'logging.debug', (['f"""file={i_file}/{num_files} station={i_station}/{num_stations} processed"""'], {}), "(\n f'file={i_file}/{num_files} station={i_station}/{num_stations} processed')\n", (9619, 9699), False, 'import logging\n'), ((10250, 10286), 'numpy.ones', 'np.ones', (['num_days_recent'], {'dtype': 'bool'}), '(num_days_recent, dtype=bool)\n', (10257, 10286), True, 'import numpy as np\n'), ((10296, 10336), 'numpy.zeros', 'np.zeros', (['num_days_preceding'], {'dtype': 'bool'}), '(num_days_preceding, dtype=bool)\n', (10304, 10336), True, 'import numpy as np\n'), ((12575, 12602), 'logging.debug', 'logging.debug', (['"""proceeding"""'], {}), "('proceeding')\n", (12588, 12602), False, 'import logging\n'), ((16230, 16255), 'logging.debug', 'logging.debug', (['"""skipping"""'], {}), "('skipping')\n", (16243, 16255), False, 'import logging\n'), ((17633, 17648), 'dfply.mask', 'mask', (['X.dq_flag'], {}), '(X.dq_flag)\n', (17637, 17648), False, 'from dfply import X, group_by, summarize, mask, n, transmute, select, left_join, ungroup, arrange, mutate\n'), ((20746, 20771), 'dfply.mask', 'mask', (["(X.element == 'PRCP')"], {}), "(X.element == 'PRCP')\n", (20750, 20771), False, 'from dfply import X, group_by, summarize, mask, n, transmute, select, left_join, ungroup, arrange, mutate\n'), ((21694, 21707), 'dfply.mask', 'mask', (['(~X.indb)'], {}), '(~X.indb)\n', (21698, 21707), False, 'from dfply import X, group_by, summarize, mask, n, transmute, select, left_join, ungroup, arrange, mutate\n'), ((21746, 21763), 'dfply.select', 'select', (['X.prcp_mm'], {}), '(X.prcp_mm)\n', (21752, 21763), False, 'from dfply import X, group_by, summarize, mask, n, transmute, select, left_join, ungroup, arrange, mutate\n'), ((22577, 22613), 'numpy.where', 'np.where', (['(x1[sortindex1] == point[0])'], {}), '(x1[sortindex1] == point[0])\n', (22585, 22613), True, 'import numpy as np\n'), ((22629, 22665), 'numpy.where', 'np.where', (['(x2[sortindex2] == point[1])'], {}), '(x2[sortindex2] == point[1])\n', (22637, 22665), True, 'import numpy as np\n'), ((26875, 26893), 'numpy.full', 'np.full', (['(5)', 'np.nan'], {}), '(5, np.nan)\n', (26882, 26893), True, 'import numpy as np\n'), ((26914, 26932), 'numpy.full', 'np.full', (['(5)', 'np.nan'], {}), '(5, np.nan)\n', (26921, 26932), True, 'import numpy as np\n'), ((27466, 27499), 'pandas.DataFrame', 'pd.DataFrame', (['qlist'], {'columns': 'cols'}), '(qlist, columns=cols)\n', (27478, 27499), True, 'import pandas as pd\n'), ((28325, 28354), 'pandas.DataFrame', 'pd.DataFrame', (['q'], {'columns': 'cols'}), '(q, columns=cols)\n', (28337, 28354), True, 'import pandas as pd\n'), ((30749, 30766), 'numpy.log10', 'np.log10', (['(0.1 * y)'], {}), '(0.1 * y)\n', (30757, 30766), True, 'import numpy as np\n'), ((38615, 38646), 'dfply.mask', 'mask', (['(X.dateto <= data_end_date)'], {}), '(X.dateto <= data_end_date)\n', (38619, 38646), False, 'from dfply import X, group_by, summarize, mask, n, transmute, select, left_join, ungroup, arrange, mutate\n'), ((43786, 43816), 'dfply.left_join', 'left_join', (['prcp0'], {'by': '"""station"""'}), "(prcp0, by='station')\n", (43795, 43816), False, 'from dfply import X, group_by, summarize, mask, n, transmute, select, left_join, ungroup, arrange, mutate\n'), ((46173, 46210), 'numpy.flatnonzero', 'np.flatnonzero', (['(station_name == index)'], {}), '(station_name == index)\n', (46187, 46210), True, 'import numpy as np\n'), ((50143, 50166), 'dfply.group_by', 'group_by', (['X.bucket_mark'], {}), '(X.bucket_mark)\n', (50151, 50166), False, 'from dfply import X, group_by, summarize, mask, n, transmute, select, left_join, ungroup, arrange, mutate\n'), ((53392, 53424), 'pandas.concat', 'pd.concat', (['[df2, totals]'], {'axis': '(0)'}), '([df2, totals], axis=0)\n', (53401, 53424), True, 'import pandas as pd\n'), ((1039, 1054), 'numpy.isnan', 'np.isnan', (['xdata'], {}), '(xdata)\n', (1047, 1054), True, 'import numpy as np\n'), ((1311, 1325), 'numpy.sum', 'np.sum', (['counts'], {}), '(counts)\n', (1317, 1325), True, 'import numpy as np\n'), ((1709, 1730), 'numpy.sum', 'np.sum', (['sample_weight'], {}), '(sample_weight)\n', (1715, 1730), True, 'import numpy as np\n'), ((4830, 4855), 'dfply.mask', 'mask', (["(X.element == 'PRCP')"], {}), "(X.element == 'PRCP')\n", (4834, 4855), False, 'from dfply import X, group_by, summarize, mask, n, transmute, select, left_join, ungroup, arrange, mutate\n'), ((5378, 5403), 'dfply.mask', 'mask', (["(X.element == 'PRCP')"], {}), "(X.element == 'PRCP')\n", (5382, 5403), False, 'from dfply import X, group_by, summarize, mask, n, transmute, select, left_join, ungroup, arrange, mutate\n'), ((5412, 5456), 'dfply.X.station.str.startswith', 'X.station.str.startswith', (['station_startswith'], {}), '(station_startswith)\n', (5436, 5456), False, 'from dfply import X, group_by, summarize, mask, n, transmute, select, left_join, ungroup, arrange, mutate\n'), ((6851, 6865), 'dfply.X.dateto.max', 'X.dateto.max', ([], {}), '()\n', (6863, 6865), False, 'from dfply import X, group_by, summarize, mask, n, transmute, select, left_join, ungroup, arrange, mutate\n'), ((7291, 7305), 'dfply.X.dateto.min', 'X.dateto.min', ([], {}), '()\n', (7303, 7305), False, 'from dfply import X, group_by, summarize, mask, n, transmute, select, left_join, ungroup, arrange, mutate\n'), ((7311, 7325), 'dfply.X.dateto.max', 'X.dateto.max', ([], {}), '()\n', (7323, 7325), False, 'from dfply import X, group_by, summarize, mask, n, transmute, select, left_join, ungroup, arrange, mutate\n'), ((8424, 8443), 'dfply.group_by', 'group_by', (['X.station'], {}), '(X.station)\n', (8432, 8443), False, 'from dfply import X, group_by, summarize, mask, n, transmute, select, left_join, ungroup, arrange, mutate\n'), ((9272, 9296), 'dfply.select', 'select', (['X.dateto', 'X.prcp'], {}), '(X.dateto, X.prcp)\n', (9278, 9296), False, 'from dfply import X, group_by, summarize, mask, n, transmute, select, left_join, ungroup, arrange, mutate\n'), ((14071, 14115), 'dfply.left_join', 'left_join', (['df_update_preceding'], {'by': '"""station"""'}), "(df_update_preceding, by='station')\n", (14080, 14115), False, 'from dfply import X, group_by, summarize, mask, n, transmute, select, left_join, ungroup, arrange, mutate\n'), ((17688, 17709), 'dfply.X.drought_index.min', 'X.drought_index.min', ([], {}), '()\n', (17707, 17709), False, 'from dfply import X, group_by, summarize, mask, n, transmute, select, left_join, ungroup, arrange, mutate\n'), ((17726, 17756), 'dfply.X.drought_index.quantile', 'X.drought_index.quantile', (['(0.25)'], {}), '(0.25)\n', (17750, 17756), False, 'from dfply import X, group_by, summarize, mask, n, transmute, select, left_join, ungroup, arrange, mutate\n'), ((17773, 17802), 'dfply.X.drought_index.quantile', 'X.drought_index.quantile', (['(0.5)'], {}), '(0.5)\n', (17797, 17802), False, 'from dfply import X, group_by, summarize, mask, n, transmute, select, left_join, ungroup, arrange, mutate\n'), ((17820, 17850), 'dfply.X.drought_index.quantile', 'X.drought_index.quantile', (['(0.75)'], {}), '(0.75)\n', (17844, 17850), False, 'from dfply import X, group_by, summarize, mask, n, transmute, select, left_join, ungroup, arrange, mutate\n'), ((17867, 17888), 'dfply.X.drought_index.max', 'X.drought_index.max', ([], {}), '()\n', (17886, 17888), False, 'from dfply import X, group_by, summarize, mask, n, transmute, select, left_join, ungroup, arrange, mutate\n'), ((23308, 23338), 'geopy.distance.geodesic', 'geodesic', (['point', 'station_point'], {}), '(point, station_point)\n', (23316, 23338), False, 'from geopy.distance import geodesic\n'), ((25297, 25325), 'datetime.date', 'date', (['d.year', 'd.month', 'd.day'], {}), '(d.year, d.month, d.day)\n', (25301, 25325), False, 'from datetime import timedelta, date, datetime\n'), ((40298, 40335), 'geopy.distance.geodesic', 'geodesic', (['center_point', 'station_point'], {}), '(center_point, station_point)\n', (40306, 40335), False, 'from geopy.distance import geodesic\n'), ((50060, 50086), 'numpy.arange', 'np.arange', (['(0)', 'num_stations'], {}), '(0, num_stations)\n', (50069, 50086), True, 'import numpy as np\n'), ((50203, 50225), 'dfply.X.drought_index.mean', 'X.drought_index.mean', ([], {}), '()\n', (50223, 50225), False, 'from dfply import X, group_by, summarize, mask, n, transmute, select, left_join, ungroup, arrange, mutate\n'), ((50248, 50269), 'dfply.X.cum_fillrate.mean', 'X.cum_fillrate.mean', ([], {}), '()\n', (50267, 50269), False, 'from dfply import X, group_by, summarize, mask, n, transmute, select, left_join, ungroup, arrange, mutate\n'), ((50291, 50309), 'dfply.n', 'n', (['X.drought_index'], {}), '(X.drought_index)\n', (50292, 50309), False, 'from dfply import X, group_by, summarize, mask, n, transmute, select, left_join, ungroup, arrange, mutate\n'), ((52920, 52939), 'dfply.group_by', 'group_by', (['X.station'], {}), '(X.station)\n', (52928, 52939), False, 'from dfply import X, group_by, summarize, mask, n, transmute, select, left_join, ungroup, arrange, mutate\n'), ((53997, 54046), 'numpy.tan', 'np.tan', (['(np.pi / 4.0 + lat * (np.pi / 180.0) / 2.0)'], {}), '(np.pi / 4.0 + lat * (np.pi / 180.0) / 2.0)\n', (54003, 54046), True, 'import numpy as np\n'), ((1274, 1303), 'numpy.cumsum', 'np.cumsum', (['counts[sort_index]'], {}), '(counts[sort_index])\n', (1283, 1303), True, 'import numpy as np\n'), ((1411, 1426), 'numpy.isnan', 'np.isnan', (['xdata'], {}), '(xdata)\n', (1419, 1426), True, 'import numpy as np\n'), ((1430, 1447), 'numpy.isnan', 'np.isnan', (['weights'], {}), '(weights)\n', (1438, 1447), True, 'import numpy as np\n'), ((1659, 1683), 'numpy.cumsum', 'np.cumsum', (['sample_weight'], {}), '(sample_weight)\n', (1668, 1683), True, 'import numpy as np\n'), ((8475, 8484), 'dfply.n', 'n', (['X.prcp'], {}), '(X.prcp)\n', (8476, 8484), False, 'from dfply import X, group_by, summarize, mask, n, transmute, select, left_join, ungroup, arrange, mutate\n'), ((9242, 9268), 'dfply.mask', 'mask', (['(X.station == station)'], {}), '(X.station == station)\n', (9246, 9268), False, 'from dfply import X, group_by, summarize, mask, n, transmute, select, left_join, ungroup, arrange, mutate\n'), ((12779, 12798), 'dfply.group_by', 'group_by', (['X.station'], {}), '(X.station)\n', (12787, 12798), False, 'from dfply import X, group_by, summarize, mask, n, transmute, select, left_join, ungroup, arrange, mutate\n'), ((13414, 13433), 'dfply.group_by', 'group_by', (['X.station'], {}), '(X.station)\n', (13422, 13433), False, 'from dfply import X, group_by, summarize, mask, n, transmute, select, left_join, ungroup, arrange, mutate\n'), ((14008, 14049), 'dfply.left_join', 'left_join', (['df_update_recent'], {'by': '"""station"""'}), "(df_update_recent, by='station')\n", (14017, 14049), False, 'from dfply import X, group_by, summarize, mask, n, transmute, select, left_join, ungroup, arrange, mutate\n'), ((52970, 52982), 'dfply.X.prcp.sum', 'X.prcp.sum', ([], {}), '()\n', (52980, 52982), False, 'from dfply import X, group_by, summarize, mask, n, transmute, select, left_join, ungroup, arrange, mutate\n'), ((53006, 53015), 'dfply.n', 'n', (['X.prcp'], {}), '(X.prcp)\n', (53007, 53015), False, 'from dfply import X, group_by, summarize, mask, n, transmute, select, left_join, ungroup, arrange, mutate\n'), ((12724, 12757), 'dfply.left_join', 'left_join', (['df_update'], {'by': '"""dateto"""'}), "(df_update, by='dateto')\n", (12733, 12757), False, 'from dfply import X, group_by, summarize, mask, n, transmute, select, left_join, ungroup, arrange, mutate\n'), ((12872, 12881), 'dfply.n', 'n', (['X.prcp'], {}), '(X.prcp)\n', (12873, 12881), False, 'from dfply import X, group_by, summarize, mask, n, transmute, select, left_join, ungroup, arrange, mutate\n'), ((13359, 13392), 'dfply.left_join', 'left_join', (['df_update'], {'by': '"""dateto"""'}), "(df_update, by='dateto')\n", (13368, 13392), False, 'from dfply import X, group_by, summarize, mask, n, transmute, select, left_join, ungroup, arrange, mutate\n'), ((13510, 13519), 'dfply.n', 'n', (['X.prcp'], {}), '(X.prcp)\n', (13511, 13519), False, 'from dfply import X, group_by, summarize, mask, n, transmute, select, left_join, ungroup, arrange, mutate\n'), ((12927, 12939), 'dfply.X.prcp.sum', 'X.prcp.sum', ([], {}), '()\n', (12937, 12939), False, 'from dfply import X, group_by, summarize, mask, n, transmute, select, left_join, ungroup, arrange, mutate\n'), ((13568, 13580), 'dfply.X.prcp.sum', 'X.prcp.sum', ([], {}), '()\n', (13578, 13580), False, 'from dfply import X, group_by, summarize, mask, n, transmute, select, left_join, ungroup, arrange, mutate\n')]
# Copyright (c) 2020 <NAME> and <NAME> # # Permission 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: # # The above copyright notice and this permission notice shall be included in all # copies or substantial portions of the Software. # # THE 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. import numpy as np import glob import os import argparse from tqdm import tqdm import librosa from video_utils import VideoProcessor def preprocess_video(dataset_folder): output_folder = os.path.join(dataset_folder, "preprocessed") landmark_folder = os.path.join(dataset_folder, "landmarks") for each_actor in glob.glob(os.path.join(dataset_folder, "Actor*")): actor_name = os.path.basename(each_actor) output_actor_folder = os.path.join(output_folder, actor_name) if not os.path.exists(output_actor_folder): os.makedirs(output_actor_folder) for each_video in glob.glob(os.path.join(each_actor, "*.mp4")): name = each_video.split("/")[-1].split("-")[0] if int(name) == 2: continue video_name = os.path.basename(each_video) landmark_path = os.path.join(landmark_folder, video_name[:-4] + '.csv') frames_folder = os.path.join(output_actor_folder, video_name) if not os.path.exists(frames_folder): os.mkdir(frames_folder) video_processor = VideoProcessor(video_path=each_video, landmark_path=landmark_path, output_folder=frames_folder, extract_audio=True) video_processor.preprocess(seq_len=30, target_resolution=(224, 224)) def get_audio_paths(path): audio_files = [] actors = os.listdir(path) for a in actors: path_to_folders = os.path.join(path, a) folders = os.listdir(path_to_folders) audio_files += [os.path.join(path_to_folders, p) for p in folders] return audio_files def mfcc_features(dataset_folder): path = os.path.join(dataset_folder, "preprocessed") files = get_audio_paths(path) for f in tqdm(files): X, sample_rate = librosa.load(os.path.join(f, 'audios/audio.wav'), duration=2.45, sr=22050 * 2, offset=0.5) sample_rate = np.array(sample_rate) mfccs = librosa.feature.mfcc(y=X, sr=sample_rate, n_mfcc=13) np.save(os.path.join(f, 'audios/featuresMFCC.npy'), mfccs) if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument('--datadir', type=str, help='dataset directory', default='RAVDESS') args = parser.parse_args() print("Processing videos...") preprocess_video(args.datadir) print("Generating MFCC features...") mfcc_features(args.datadir) print("Preprocessed dataset located in ", os.path.join(args.datadir, 'preprocessed'))
[ "os.mkdir", "tqdm.tqdm", "video_utils.VideoProcessor", "argparse.ArgumentParser", "librosa.feature.mfcc", "os.path.basename", "os.makedirs", "os.path.exists", "numpy.array", "os.path.join", "os.listdir" ]
[((1290, 1334), 'os.path.join', 'os.path.join', (['dataset_folder', '"""preprocessed"""'], {}), "(dataset_folder, 'preprocessed')\n", (1302, 1334), False, 'import os\n'), ((1357, 1398), 'os.path.join', 'os.path.join', (['dataset_folder', '"""landmarks"""'], {}), "(dataset_folder, 'landmarks')\n", (1369, 1398), False, 'import os\n'), ((2516, 2532), 'os.listdir', 'os.listdir', (['path'], {}), '(path)\n', (2526, 2532), False, 'import os\n'), ((2794, 2838), 'os.path.join', 'os.path.join', (['dataset_folder', '"""preprocessed"""'], {}), "(dataset_folder, 'preprocessed')\n", (2806, 2838), False, 'import os\n'), ((2886, 2897), 'tqdm.tqdm', 'tqdm', (['files'], {}), '(files)\n', (2890, 2897), False, 'from tqdm import tqdm\n'), ((3275, 3300), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (3298, 3300), False, 'import argparse\n'), ((1432, 1470), 'os.path.join', 'os.path.join', (['dataset_folder', '"""Actor*"""'], {}), "(dataset_folder, 'Actor*')\n", (1444, 1470), False, 'import os\n'), ((1494, 1522), 'os.path.basename', 'os.path.basename', (['each_actor'], {}), '(each_actor)\n', (1510, 1522), False, 'import os\n'), ((1553, 1592), 'os.path.join', 'os.path.join', (['output_folder', 'actor_name'], {}), '(output_folder, actor_name)\n', (1565, 1592), False, 'import os\n'), ((2580, 2601), 'os.path.join', 'os.path.join', (['path', 'a'], {}), '(path, a)\n', (2592, 2601), False, 'import os\n'), ((2620, 2647), 'os.listdir', 'os.listdir', (['path_to_folders'], {}), '(path_to_folders)\n', (2630, 2647), False, 'import os\n'), ((3075, 3096), 'numpy.array', 'np.array', (['sample_rate'], {}), '(sample_rate)\n', (3083, 3096), True, 'import numpy as np\n'), ((3113, 3165), 'librosa.feature.mfcc', 'librosa.feature.mfcc', ([], {'y': 'X', 'sr': 'sample_rate', 'n_mfcc': '(13)'}), '(y=X, sr=sample_rate, n_mfcc=13)\n', (3133, 3165), False, 'import librosa\n'), ((3615, 3657), 'os.path.join', 'os.path.join', (['args.datadir', '"""preprocessed"""'], {}), "(args.datadir, 'preprocessed')\n", (3627, 3657), False, 'import os\n'), ((1609, 1644), 'os.path.exists', 'os.path.exists', (['output_actor_folder'], {}), '(output_actor_folder)\n', (1623, 1644), False, 'import os\n'), ((1658, 1690), 'os.makedirs', 'os.makedirs', (['output_actor_folder'], {}), '(output_actor_folder)\n', (1669, 1690), False, 'import os\n'), ((1728, 1761), 'os.path.join', 'os.path.join', (['each_actor', '"""*.mp4"""'], {}), "(each_actor, '*.mp4')\n", (1740, 1761), False, 'import os\n'), ((1904, 1932), 'os.path.basename', 'os.path.basename', (['each_video'], {}), '(each_video)\n', (1920, 1932), False, 'import os\n'), ((1961, 2016), 'os.path.join', 'os.path.join', (['landmark_folder', "(video_name[:-4] + '.csv')"], {}), "(landmark_folder, video_name[:-4] + '.csv')\n", (1973, 2016), False, 'import os\n'), ((2045, 2090), 'os.path.join', 'os.path.join', (['output_actor_folder', 'video_name'], {}), '(output_actor_folder, video_name)\n', (2057, 2090), False, 'import os\n'), ((2211, 2330), 'video_utils.VideoProcessor', 'VideoProcessor', ([], {'video_path': 'each_video', 'landmark_path': 'landmark_path', 'output_folder': 'frames_folder', 'extract_audio': '(True)'}), '(video_path=each_video, landmark_path=landmark_path,\n output_folder=frames_folder, extract_audio=True)\n', (2225, 2330), False, 'from video_utils import VideoProcessor\n'), ((2672, 2704), 'os.path.join', 'os.path.join', (['path_to_folders', 'p'], {}), '(path_to_folders, p)\n', (2684, 2704), False, 'import os\n'), ((2937, 2972), 'os.path.join', 'os.path.join', (['f', '"""audios/audio.wav"""'], {}), "(f, 'audios/audio.wav')\n", (2949, 2972), False, 'import os\n'), ((3182, 3224), 'os.path.join', 'os.path.join', (['f', '"""audios/featuresMFCC.npy"""'], {}), "(f, 'audios/featuresMFCC.npy')\n", (3194, 3224), False, 'import os\n'), ((2110, 2139), 'os.path.exists', 'os.path.exists', (['frames_folder'], {}), '(frames_folder)\n', (2124, 2139), False, 'import os\n'), ((2157, 2180), 'os.mkdir', 'os.mkdir', (['frames_folder'], {}), '(frames_folder)\n', (2165, 2180), False, 'import os\n')]
# Run me as follows: # cd tests/ # nosetests -v -s test_utils.py import copy import librosa import numpy as np import os # Msaf imports import msaf # Global vars audio_file = os.path.join("fixtures", "chirp.mp3") sr = msaf.config.sample_rate audio, fs = librosa.load(audio_file, sr=sr) y_harmonic, y_percussive = librosa.effects.hpss(audio) def test_synchronize_labels(): old_bound_idxs = [0, 82, 150, 268, 342, 353, 463, 535, 616, 771, 833, 920, 979, 1005] new_bound_idxs = [0, 229, 337, 854, 929, 994, 1004] labels = [4, 6, 2, 0, 0, 2, 5, 3, 0, 5, 1, 5, 1] N = 1005 new_labels = msaf.utils.synchronize_labels(new_bound_idxs, old_bound_idxs, labels, N) assert len(new_labels) == len(new_bound_idxs) - 1 def test_get_num_frames(): dur = 320.2 anal = {"sample_rate": 22050, "hop_size": 512} n_frames = msaf.utils.get_num_frames(dur, anal) assert n_frames == int(dur * anal["sample_rate"] / anal["hop_size"]) def test_get_time_frames(): dur = 1 anal = {"sample_rate": 22050, "hop_size": 512} n_frames = msaf.utils.get_time_frames(dur, anal) assert n_frames.shape[0] == 43 assert n_frames[0] == 0.0 assert n_frames[-1] == 1.0 def test_align_end_hierarchies(): def _test_equal_hier(hier_orig, hier_new): for layer_orig, layer_new in zip(hier_orig, hier_new): assert layer_orig == layer_new hier1 = [[0, 10, 20, 30], [0, 30]] hier2 = [[0, 5, 40, 50], [0, 50]] hier1_orig = copy.deepcopy(hier1) hier2_orig = copy.deepcopy(hier2) msaf.utils.align_end_hierarchies(hier1, hier2) yield (_test_equal_hier, hier1_orig, hier1) yield (_test_equal_hier, hier2_orig, hier2) def test_lognormalize(): # Just check that we're not overwriting data X = np.random.random((300, 10)) Y = msaf.utils.lognormalize(X) assert not np.array_equal(X, Y) def test_min_max_normalize(): # Just check that we're not overwriting data X = np.random.random((300, 10)) Y = msaf.utils.min_max_normalize(X) assert not np.array_equal(X, Y)
[ "copy.deepcopy", "msaf.utils.synchronize_labels", "msaf.utils.min_max_normalize", "msaf.utils.get_time_frames", "librosa.effects.hpss", "msaf.utils.get_num_frames", "librosa.load", "numpy.random.random", "msaf.utils.align_end_hierarchies", "numpy.array_equal", "msaf.utils.lognormalize", "os.pa...
[((177, 214), 'os.path.join', 'os.path.join', (['"""fixtures"""', '"""chirp.mp3"""'], {}), "('fixtures', 'chirp.mp3')\n", (189, 214), False, 'import os\n'), ((256, 287), 'librosa.load', 'librosa.load', (['audio_file'], {'sr': 'sr'}), '(audio_file, sr=sr)\n', (268, 287), False, 'import librosa\n'), ((315, 342), 'librosa.effects.hpss', 'librosa.effects.hpss', (['audio'], {}), '(audio)\n', (335, 342), False, 'import librosa\n'), ((627, 699), 'msaf.utils.synchronize_labels', 'msaf.utils.synchronize_labels', (['new_bound_idxs', 'old_bound_idxs', 'labels', 'N'], {}), '(new_bound_idxs, old_bound_idxs, labels, N)\n', (656, 699), False, 'import msaf\n'), ((1006, 1042), 'msaf.utils.get_num_frames', 'msaf.utils.get_num_frames', (['dur', 'anal'], {}), '(dur, anal)\n', (1031, 1042), False, 'import msaf\n'), ((1224, 1261), 'msaf.utils.get_time_frames', 'msaf.utils.get_time_frames', (['dur', 'anal'], {}), '(dur, anal)\n', (1250, 1261), False, 'import msaf\n'), ((1642, 1662), 'copy.deepcopy', 'copy.deepcopy', (['hier1'], {}), '(hier1)\n', (1655, 1662), False, 'import copy\n'), ((1680, 1700), 'copy.deepcopy', 'copy.deepcopy', (['hier2'], {}), '(hier2)\n', (1693, 1700), False, 'import copy\n'), ((1706, 1752), 'msaf.utils.align_end_hierarchies', 'msaf.utils.align_end_hierarchies', (['hier1', 'hier2'], {}), '(hier1, hier2)\n', (1738, 1752), False, 'import msaf\n'), ((1934, 1961), 'numpy.random.random', 'np.random.random', (['(300, 10)'], {}), '((300, 10))\n', (1950, 1961), True, 'import numpy as np\n'), ((1970, 1996), 'msaf.utils.lognormalize', 'msaf.utils.lognormalize', (['X'], {}), '(X)\n', (1993, 1996), False, 'import msaf\n'), ((2122, 2149), 'numpy.random.random', 'np.random.random', (['(300, 10)'], {}), '((300, 10))\n', (2138, 2149), True, 'import numpy as np\n'), ((2158, 2189), 'msaf.utils.min_max_normalize', 'msaf.utils.min_max_normalize', (['X'], {}), '(X)\n', (2186, 2189), False, 'import msaf\n'), ((2012, 2032), 'numpy.array_equal', 'np.array_equal', (['X', 'Y'], {}), '(X, Y)\n', (2026, 2032), True, 'import numpy as np\n'), ((2205, 2225), 'numpy.array_equal', 'np.array_equal', (['X', 'Y'], {}), '(X, Y)\n', (2219, 2225), True, 'import numpy as np\n')]
import numpy as np import pandas as pd import geopandas as gpd import jenkspy us_state_abbrev = { 'Alabama': 'AL', 'Alaska': 'AK', 'American Samoa': 'AS', 'Arizona': 'AZ', 'Arkansas': 'AR', 'California': 'CA', 'Colorado': 'CO', 'Connecticut': 'CT', 'Delaware': 'DE', 'District of Columbia': 'DC', 'Florida': 'FL', 'Georgia': 'GA', 'Guam': 'GU', 'Hawaii': 'HI', 'Idaho': 'ID', 'Illinois': 'IL', 'Indiana': 'IN', 'Iowa': 'IA', 'Kansas': 'KS', 'Kentucky': 'KY', 'Louisiana': 'LA', 'Maine': 'ME', 'Maryland': 'MD', 'Massachusetts': 'MA', 'Michigan': 'MI', 'Minnesota': 'MN', 'Mississippi': 'MS', 'Missouri': 'MO', 'Montana': 'MT', 'Nebraska': 'NE', 'Nevada': 'NV', 'New Hampshire': 'NH', 'New Jersey': 'NJ', 'New Mexico': 'NM', 'New York': 'NY', 'North Carolina': 'NC', 'North Dakota': 'ND', 'Northern Mariana Islands':'MP', 'Ohio': 'OH', 'Oklahoma': 'OK', 'Oregon': 'OR', 'Pennsylvania': 'PA', 'Puerto Rico': 'PR', 'Rhode Island': 'RI', 'South Carolina': 'SC', 'South Dakota': 'SD', 'Tennessee': 'TN', 'Texas': 'TX', 'Utah': 'UT', 'Vermont': 'VT', 'Virgin Islands': 'VI', 'Virginia': 'VA', 'Washington': 'WA', 'West Virginia': 'WV', 'Wisconsin': 'WI', 'Wyoming': 'WY' } class GetData(object): """docstring for GetData""" def __init__(self,start_date='2000-01-01'): super(GetData, self).__init__() self.can_province_names = { 'AB': 'Alberta', 'BC': 'British Columbia', 'MB': 'Manitoba', 'NB': 'New Brunswick', 'NL': 'Newfoundland and Labrador', 'NS': 'Nova Scotia', 'NT': 'Northwest Territories', 'NU': 'Nunavut', 'ON': 'Ontario', 'PE': 'Prince Edward Island', 'QC': 'Quebec', 'SK': 'Saskatchewan', 'YT': 'Yukon' } self.can_province_abbrev = { 'Alberta': 'AB', 'British Columbia': 'BC', 'Manitoba': 'MB', 'New Brunswick': 'NB', 'Newfoundland and Labrador': 'NL', 'Northwest Territories': 'NT', 'Nova Scotia': 'NS', 'Nunavut': 'NU', 'Ontario': 'ON', 'Prince Edward Island': 'PE', 'Quebec': 'QC', 'Saskatchewan': 'SK', 'Yukon': 'YT' } # Import Canadian Data self.CA_PoliceKillings = pd.read_csv('Inputs/PID_Canada.csv', parse_dates=['date'], index_col=['id_victim'] ) self.CA_PoliceKillings=self.CA_PoliceKillings.set_index(pd.DatetimeIndex(self.CA_PoliceKillings['date']), drop=True ) self.CA_PoliceKillings=self.CA_PoliceKillings.loc[self.CA_PoliceKillings.index>=start_date] self.CA_PoliceKillings['armed_type'] = self.CA_PoliceKillings['armed_type'].replace({ 'Air gun, replica gun':'Other weapons', 'Bat, club, other swinging object':'Other weapons', 'Vehicle':'Other weapons', 'Knife, axe, other cutting instruments':'Knife', 'Unknown':'None', 'Chemical or sprays':'Other weapons'}) self.CA_PoliceKillings['race'] = self.CA_PoliceKillings['race'].replace({ 'Other':'Visible minority, n.i.e', 'Caucasian':'Visible minority, n.i.e'}) self.CA_PoliceKillings.race.fillna('Unknown',inplace=True) self.CA_PoliceKillings['department'] = self.CA_PoliceKillings['department'].replace({ # 'Service de police de la Ville de Lévis, Sûreté du Québec':'Service de police de la Ville de Lévis', # 'Sûreté du Québec':'SQ', 'Peterborough Lakefield Community Police Force':'Peterborough Police Service', 'OPP':'Ontario Provincial Police', # # 'Service de police de la Ville de Montréal':'Montreal Police Service' }) CA_Census = pd.read_csv('Inputs/Canadian_Census_2016.csv', index_col=['PRUID'] ) CA_Census = CA_Census.rename(columns={ 'Caucasian':'White'}) CA_Census['Asian'] = CA_Census['Chinese']+CA_Census['Filipino']+CA_Census['West Asian']+\ CA_Census['Japanese']+CA_Census['Korean']+CA_Census['Southeast Asian'] CA_Census = CA_Census.drop(['Chinese','Filipino','West Asian','Japanese','Korean','Southeast Asian'],axis=1) CA_Census['Unknown'] = 0 CA_Census['Visible minority, n.i.e'] = CA_Census['Visible minority, n.i.e']+CA_Census['Multiple visible minorities'] CA_Census = CA_Census.drop(['Multiple visible minorities'],axis=1) CA_Provinces= gpd.read_file('Inputs/Canadian_Census_Boundaries_2016.shp').set_index('PRUID') dtype = 'int64' CA_Provinces.index = CA_Provinces.index.astype(dtype) CA_Provinces= CA_Provinces.join(CA_Census) # CA_Provinces= CA_Provinces.rename(columns={'Caucasian':'White'}) CA_Provinces= CA_Provinces.set_index('prov') Municipal = pd.read_csv('Inputs/Municipal_Data.csv',index_col=['GEO UID'], encoding= 'utf-8') Municipal.loc[Municipal['Caucasian']<0,'Caucasian']=0 Municipal = Municipal.rename(columns={ 'Caucasian':'White'}) Municipal['Asian'] = Municipal['Chinese']+Municipal['Filipino']+Municipal['West Asian']+\ Municipal['Japanese']+Municipal['Korean']+Municipal['Southeast Asian'] Municipal = Municipal.drop(['Chinese','Filipino','West Asian','Japanese','Korean','Southeast Asian'],axis=1) Municipal['Unknown'] = 0 Municipal['Visible minority, n.i.e'] = Municipal['Visible minority, n.i.e']+Municipal['Multiple visible minorities'] Municipal = Municipal.drop(['Multiple visible minorities'],axis=1) Municipal_Boundaries=gpd.read_file('Inputs/lcsd000a14a_e.shp') Municipal_Boundaries = Municipal_Boundaries.set_index( Municipal_Boundaries['CSDUID'].astype( Municipal.index.dtype)) self.Municipal_Boundaries=Municipal_Boundaries.join(Municipal) self.Municipal_Boundaries['PROV']=self.Municipal_Boundaries['PRNAME'].str.split(' / ',expand=True)[0] # self.Municipal_Boundaries = self.Municipal_Boundaries.rename(columns={ # 'Caucasian':'White'}) self.Municipal_Boundaries['Name']=self.Municipal_Boundaries['Name'].astype(str).str[:-1] # Import and Parse United States Data self.US_PoliceKillings = pd.read_csv('Inputs/PoliceKillings_US.csv', parse_dates=['Date of Incident (month/day/year)'], index_col=['MPV ID'], encoding= 'unicode_escape' ) self.US_PoliceKillings=self.US_PoliceKillings.set_index(pd.DatetimeIndex(self.US_PoliceKillings['Date of Incident (month/day/year)']), drop=True ) self.US_PoliceKillings=self.US_PoliceKillings.loc[self.US_PoliceKillings.index>=start_date] self.US_PoliceKillings['RACE']=self.US_PoliceKillings["Victim's race"].replace({ 'Native American':'Indigenous', 'unknown race':'Unknown', 'Unknown race':'Unknown'}) self.US_PoliceKillings['RACE'].fillna('Unknown') self.US_PoliceKillings['Armed/Unarmed Status']=self.US_PoliceKillings['Armed/Unarmed Status'].replace({ 'unclear':'Unarmed', 'Unclear':'Unarmed', 'Unarmed/Did Not Have Actual Weapon':'Unarmed', 'Unarmed/Did Not Have An Actual Weapon':'Unarmed', 'Unarmed/Did Not Have an Actual Weapon':'Unarmed', 'Allegedly armed':'Allegedly Armed' }) # self.US_PoliceKillings.loc[self.US_PoliceKillings["Victim's race"]=='Native America',"Victim's race"]='Indigenous' self.US_PoliceKillings['AGE']=self.US_PoliceKillings["Victim's age"].replace({ 'Unknown':np.nan,'40s':np.nan}).astype(float) US_Census_Detailed = pd.read_csv('Inputs/US_Census_Data_2018.csv',skiprows=1, index_col=['id'], ) vals = ['Geographic Area Name'] rename = {'Geographic Area Name':'State'} for v in US_Census_Detailed.columns.values: if v.split('!!')[0]=='Estimate' and len(v.split('!!'))==5: if v.split('!!')[3]=='One race': vals.append(v) rename[v]=v.split('!!')[-1] if v == 'Estimate!!HISPANIC OR LATINO AND RACE!!Total population': vals.append(v) rename[v]='Hispanic' US_Census = US_Census_Detailed[vals] US_Census=US_Census.rename(columns=rename) for i in US_Census_Detailed['Geographic Area Name']: US_Census.loc[US_Census['State']==i,'State']=us_state_abbrev[i] US_Census=US_Census.rename(columns={'Black or African American':'Black', 'American Indian and Alaska Native':'Indigenous', 'Native Hawaiian and Other Pacific Islander':'Pacific Islander', }) US_Census['Total']=US_Census_Detailed['Estimate!!SEX AND AGE!!Total population'] US_Census['Mixed']=US_Census_Detailed['Estimate!!RACE!!Total population!!Two or more races'] US_States= gpd.read_file('Inputs/cb_2018_us_state_20m.shp').set_index('AFFGEOID') US_States= US_States.join(US_Census) US_States= US_States.set_index('STUSPS') self.CA_Length=(self.CA_PoliceKillings.index.max()-self.CA_PoliceKillings.index.min()).days/365.25 self.US_Length=(self.US_PoliceKillings.index.max()-self.US_PoliceKillings.index.min()).days/365.25 ## Subset CA_Provincesdata by province and join CA_Killings_By_Race = (self.CA_PoliceKillings.groupby(['prov','race']).count()['gender'].unstack()) self.CA_PoliceKillings['Year'] = self.CA_PoliceKillings.index.year CA_Killings_By_Year = (self.CA_PoliceKillings.groupby(['prov','Year']).count()['gender'].unstack()) #Join to the geodataframe self.CA = CA_Provinces.join(self.CA_PoliceKillings.groupby('prov').count()["department"]) self.CA = self.CA.rename(columns={'department':'Total_Killings'}) self.CA = self.CA.join(CA_Killings_By_Race,rsuffix='_Killings') # self.CA = self.CA.rename(columns={'Unknown':'Unknown_Killings'}) self.CA = self.CA.join(CA_Killings_By_Year) ## Subset CA_Provincesdata by province and join US_Killings_By_Race = (self.US_PoliceKillings.groupby(['State',"RACE"]).count()["Victim's age"].unstack()) self.US_PoliceKillings['Year'] = self.US_PoliceKillings.index.year US_Killings_By_Year = (self.US_PoliceKillings.groupby(['State','Year']).count()["Victim's age"].unstack()) #Join to the geodataframe self.US = US_States.join(self.US_PoliceKillings.groupby('State').count()["Victim's age"]) self.US = self.US.dropna() self.US = self.US.rename(columns={"Victim's age":'Total_Killings'}) self.US = self.US.join(US_Killings_By_Race,rsuffix='_Killings') self.US = self.US.rename(columns={'Unknown':'Unknown_Killings'}) self.US = self.US.join(US_Killings_By_Year) def ScaleData(self,scale=1,Categories=['Total','White','Black','Indigenous']): # Scale the data, fill the nulls, Categories = [v for v in self.CA_PoliceKillings.race.unique()] for c in self.US_PoliceKillings.RACE.unique(): if c not in self.CA_PoliceKillings.race.unique(): Categories.append(c) Categories.append('Total') Summary={} Summary['US']={} Summary['CA']={} CombinedCA=[] CombinedUS=[] for cat in Categories: if cat == 'Unknown': self.CA[cat+'_Rate']=self.CA[cat+'_Killings']/self.CA['Total']*scale/self.CA_Length self.CA[cat+'_Rate']=self.CA[cat+'_Rate'].fillna(0) self.US[cat+'_Rate']=self.US[cat+'_Killings']/self.US['Total']*scale/self.US_Length self.US[cat+'_Rate']=self.US[cat+'_Rate'].fillna(0) CA_Rate = self.CA[cat+'_Killings'].sum()/self.CA['Total'].sum()*scale/self.CA_Length US_Rate = self.US[cat+'_Killings'].sum()/self.US['Total'].sum()*scale/self.US_Length CombinedCA.append(cat+'_Killings') CombinedCA.append(cat+'_Rate') CombinedUS.append(cat+'_Killings') CombinedUS.append(cat+'_Rate') else: try: self.CA[cat+'_Rate']=self.CA[cat+'_Killings']/self.CA[cat]*scale/self.CA_Length self.CA[cat+'_Rate']=self.CA[cat+'_Rate'].fillna(0) CA_Rate = self.CA[cat+'_Killings'].sum()/self.CA[cat].sum()*scale/self.CA_Length CombinedCA.append(cat+'_Killings') CombinedCA.append(cat+'_Rate') CombinedCA.append(cat) Summary['CA'][cat] = CA_Rate except: pass try: self.US[cat+'_Rate']=self.US[cat+'_Killings']/self.US[cat]*scale/self.US_Length self.US[cat+'_Rate']=self.US[cat+'_Rate'].fillna(0) US_Rate = self.US[cat+'_Killings'].sum()/self.US[cat].sum()*scale/self.US_Length CombinedUS.append(cat+'_Killings') CombinedUS.append(cat+'_Rate') CombinedUS.append(cat) Summary['US'][cat] = US_Rate except: pass # Combined.append(cat+'_Killings') # Combined.append(cat+'_Rate') # try: # except: # pass # try: # except: # pass self.Summary = pd.DataFrame(data=Summary) CombinedCA.append('geometry') CombinedUS.append('geometry') CombinedCA.append('Country') CombinedUS.append('Country') # print(CombinedCA,CombinedUS) self.CA['Country'] = 'CA' self.US['Country'] = 'US' self.Combined=self.CA[CombinedCA].append(self.US[CombinedUS]) def Breaks(self,column,classes=5,labels=None,Manual_Bins=None,STD_i = 1): self.CA_jenks = jenkspy.jenks_breaks(self.CA[column], nb_class=classes) self.CA[column+'_NB'] = pd.cut(self.CA[column], bins=self.CA_jenks, labels=labels, include_lowest=True, duplicates='drop' ) self.US_jenks = jenkspy.jenks_breaks(self.US[column], nb_class=classes) self.US[column+'_NB'] = pd.cut(self.US[column], bins=self.US_jenks, labels=labels, include_lowest=True ) self.Combined_jenks = jenkspy.jenks_breaks(self.Combined[column], nb_class=classes) self.Combined[column+'_NB'] = pd.cut(self.Combined[column], bins=self.Combined_jenks, labels=labels, include_lowest=True ) # Quantiles self.classes = classes self.CA[column+'_QB'] = pd.qcut(self.CA[column], q=self.classes, duplicates='drop' ) self.US[column+'_QB'] = pd.qcut(self.US[column], q=self.classes, duplicates='drop' ) self.Combined[column+'_QB'] = pd.qcut(self.Combined[column], q=self.classes, duplicates='drop' ) # Equal Intervals import math # start = math.floor(min(self.US[column].min(),self.CA[column].min())*10)/10\ start = 0 end = math.ceil(max(self.US[column].max(),self.CA[column].max())*10)/10+.1 freq = (end-start)/classes self.EB_bins = np.linspace(start,end,classes+1) self.CA[column+'_EB'] = pd.cut(self.CA[column], bins=self.EB_bins,#pd.interval_range(start=start,freq=freq,end=end,closed='neither'), labels=self.EB_bins[1:], include_lowest=True, duplicates='drop' ) self.US[column+'_EB'] = pd.cut(self.US[column], bins=self.EB_bins,#pd.interval_range(start=start,freq=freq,end=end,closed='neither'), labels=self.EB_bins[1:], include_lowest=True, duplicates='drop' ) self.Combined[column+'_EB'] = pd.cut(self.Combined[column], bins=self.EB_bins,#pd.interval_range(start=start,freq=freq,end=end,closed='neither'), labels=self.EB_bins[1:], include_lowest=True, duplicates='drop' ) # Manual Breaks if Manual_Bins != None: self.Manual_Bins = Manual_Bins self.CA[column+'_MB'] = pd.cut(self.CA[column], bins=self.Manual_Bins, labels=labels, include_lowest=True, duplicates='drop' ) self.US[column+'_MB'] = pd.cut(self.US[column], bins=self.Manual_Bins, labels=labels, include_lowest=True, duplicates='drop' ) self.Combined[column+'_MB'] = pd.cut(self.Combined[column], bins=self.Manual_Bins, labels=labels, include_lowest=True, duplicates='drop' ) self.CA['STD'] = (self.CA[column]-self.CA[column].mean())/self.CA[column].std() bins = np.arange(0,max(self.CA['STD'].min()*-1,self.CA['STD'].max())+STD_i,STD_i) self.CA_STD_bins = (np.append(bins[::-1][:-1]*-1,bins)) self.CA[column+'_STD'] = pd.cut(self.CA['STD'], bins=self.CA_STD_bins, duplicates='drop' ) self.US['STD'] = (self.US[column]-self.US[column].mean())/self.US[column].std() bins = np.arange(0,max(self.US['STD'].min()*-1,self.US['STD'].max())+STD_i,STD_i) self.US_STD_bins = (np.append(bins[::-1][:-1]*-1,bins)) self.US[column+'_STD'] = pd.cut(self.US['STD'], bins=self.US_STD_bins, duplicates='drop' ) self.Combined['STD'] = (self.Combined[column]-self.Combined[column].mean())/self.Combined[column].std() bins = np.arange(0,max(self.Combined['STD'].min()*-1,self.Combined['STD'].max())+STD_i/.5,STD_i) self.Combined_STD_bins = (np.append(bins[::-1][:-1]*-1,bins)) self.Combined[column+'_STD'] = pd.cut(self.Combined['STD'], bins=self.Combined_STD_bins, duplicates='drop' )
[ "pandas.DataFrame", "jenkspy.jenks_breaks", "pandas.read_csv", "pandas.DatetimeIndex", "pandas.cut", "numpy.append", "numpy.linspace", "pandas.qcut", "geopandas.read_file" ]
[((2530, 2618), 'pandas.read_csv', 'pd.read_csv', (['"""Inputs/PID_Canada.csv"""'], {'parse_dates': "['date']", 'index_col': "['id_victim']"}), "('Inputs/PID_Canada.csv', parse_dates=['date'], index_col=[\n 'id_victim'])\n", (2541, 2618), True, 'import pandas as pd\n'), ((4518, 4585), 'pandas.read_csv', 'pd.read_csv', (['"""Inputs/Canadian_Census_2016.csv"""'], {'index_col': "['PRUID']"}), "('Inputs/Canadian_Census_2016.csv', index_col=['PRUID'])\n", (4529, 4585), True, 'import pandas as pd\n'), ((5681, 5767), 'pandas.read_csv', 'pd.read_csv', (['"""Inputs/Municipal_Data.csv"""'], {'index_col': "['GEO UID']", 'encoding': '"""utf-8"""'}), "('Inputs/Municipal_Data.csv', index_col=['GEO UID'], encoding=\n 'utf-8')\n", (5692, 5767), True, 'import pandas as pd\n'), ((6533, 6574), 'geopandas.read_file', 'gpd.read_file', (['"""Inputs/lcsd000a14a_e.shp"""'], {}), "('Inputs/lcsd000a14a_e.shp')\n", (6546, 6574), True, 'import geopandas as gpd\n'), ((7204, 7357), 'pandas.read_csv', 'pd.read_csv', (['"""Inputs/PoliceKillings_US.csv"""'], {'parse_dates': "['Date of Incident (month/day/year)']", 'index_col': "['MPV ID']", 'encoding': '"""unicode_escape"""'}), "('Inputs/PoliceKillings_US.csv', parse_dates=[\n 'Date of Incident (month/day/year)'], index_col=['MPV ID'], encoding=\n 'unicode_escape')\n", (7215, 7357), True, 'import pandas as pd\n'), ((8885, 8960), 'pandas.read_csv', 'pd.read_csv', (['"""Inputs/US_Census_Data_2018.csv"""'], {'skiprows': '(1)', 'index_col': "['id']"}), "('Inputs/US_Census_Data_2018.csv', skiprows=1, index_col=['id'])\n", (8896, 8960), True, 'import pandas as pd\n'), ((14879, 14905), 'pandas.DataFrame', 'pd.DataFrame', ([], {'data': 'Summary'}), '(data=Summary)\n', (14891, 14905), True, 'import pandas as pd\n'), ((15337, 15392), 'jenkspy.jenks_breaks', 'jenkspy.jenks_breaks', (['self.CA[column]'], {'nb_class': 'classes'}), '(self.CA[column], nb_class=classes)\n', (15357, 15392), False, 'import jenkspy\n'), ((15425, 15528), 'pandas.cut', 'pd.cut', (['self.CA[column]'], {'bins': 'self.CA_jenks', 'labels': 'labels', 'include_lowest': '(True)', 'duplicates': '"""drop"""'}), "(self.CA[column], bins=self.CA_jenks, labels=labels, include_lowest=\n True, duplicates='drop')\n", (15431, 15528), True, 'import pandas as pd\n'), ((15701, 15756), 'jenkspy.jenks_breaks', 'jenkspy.jenks_breaks', (['self.US[column]'], {'nb_class': 'classes'}), '(self.US[column], nb_class=classes)\n', (15721, 15756), False, 'import jenkspy\n'), ((15789, 15868), 'pandas.cut', 'pd.cut', (['self.US[column]'], {'bins': 'self.US_jenks', 'labels': 'labels', 'include_lowest': '(True)'}), '(self.US[column], bins=self.US_jenks, labels=labels, include_lowest=True)\n', (15795, 15868), True, 'import pandas as pd\n'), ((16024, 16085), 'jenkspy.jenks_breaks', 'jenkspy.jenks_breaks', (['self.Combined[column]'], {'nb_class': 'classes'}), '(self.Combined[column], nb_class=classes)\n', (16044, 16085), False, 'import jenkspy\n'), ((16124, 16219), 'pandas.cut', 'pd.cut', (['self.Combined[column]'], {'bins': 'self.Combined_jenks', 'labels': 'labels', 'include_lowest': '(True)'}), '(self.Combined[column], bins=self.Combined_jenks, labels=labels,\n include_lowest=True)\n', (16130, 16219), True, 'import pandas as pd\n'), ((16420, 16479), 'pandas.qcut', 'pd.qcut', (['self.CA[column]'], {'q': 'self.classes', 'duplicates': '"""drop"""'}), "(self.CA[column], q=self.classes, duplicates='drop')\n", (16427, 16479), True, 'import pandas as pd\n'), ((16609, 16668), 'pandas.qcut', 'pd.qcut', (['self.US[column]'], {'q': 'self.classes', 'duplicates': '"""drop"""'}), "(self.US[column], q=self.classes, duplicates='drop')\n", (16616, 16668), True, 'import pandas as pd\n'), ((16804, 16869), 'pandas.qcut', 'pd.qcut', (['self.Combined[column]'], {'q': 'self.classes', 'duplicates': '"""drop"""'}), "(self.Combined[column], q=self.classes, duplicates='drop')\n", (16811, 16869), True, 'import pandas as pd\n'), ((17260, 17296), 'numpy.linspace', 'np.linspace', (['start', 'end', '(classes + 1)'], {}), '(start, end, classes + 1)\n', (17271, 17296), True, 'import numpy as np\n'), ((17354, 17465), 'pandas.cut', 'pd.cut', (['self.CA[column]'], {'bins': 'self.EB_bins', 'labels': 'self.EB_bins[1:]', 'include_lowest': '(True)', 'duplicates': '"""drop"""'}), "(self.CA[column], bins=self.EB_bins, labels=self.EB_bins[1:],\n include_lowest=True, duplicates='drop')\n", (17360, 17465), True, 'import pandas as pd\n'), ((17714, 17825), 'pandas.cut', 'pd.cut', (['self.US[column]'], {'bins': 'self.EB_bins', 'labels': 'self.EB_bins[1:]', 'include_lowest': '(True)', 'duplicates': '"""drop"""'}), "(self.US[column], bins=self.EB_bins, labels=self.EB_bins[1:],\n include_lowest=True, duplicates='drop')\n", (17720, 17825), True, 'import pandas as pd\n'), ((18080, 18197), 'pandas.cut', 'pd.cut', (['self.Combined[column]'], {'bins': 'self.EB_bins', 'labels': 'self.EB_bins[1:]', 'include_lowest': '(True)', 'duplicates': '"""drop"""'}), "(self.Combined[column], bins=self.EB_bins, labels=self.EB_bins[1:],\n include_lowest=True, duplicates='drop')\n", (18086, 18197), True, 'import pandas as pd\n'), ((19673, 19710), 'numpy.append', 'np.append', (['(bins[::-1][:-1] * -1)', 'bins'], {}), '(bins[::-1][:-1] * -1, bins)\n', (19682, 19710), True, 'import numpy as np\n'), ((19742, 19806), 'pandas.cut', 'pd.cut', (["self.CA['STD']"], {'bins': 'self.CA_STD_bins', 'duplicates': '"""drop"""'}), "(self.CA['STD'], bins=self.CA_STD_bins, duplicates='drop')\n", (19748, 19806), True, 'import pandas as pd\n'), ((20110, 20147), 'numpy.append', 'np.append', (['(bins[::-1][:-1] * -1)', 'bins'], {}), '(bins[::-1][:-1] * -1, bins)\n', (20119, 20147), True, 'import numpy as np\n'), ((20179, 20243), 'pandas.cut', 'pd.cut', (["self.US['STD']"], {'bins': 'self.US_STD_bins', 'duplicates': '"""drop"""'}), "(self.US['STD'], bins=self.US_STD_bins, duplicates='drop')\n", (20185, 20243), True, 'import pandas as pd\n'), ((20592, 20629), 'numpy.append', 'np.append', (['(bins[::-1][:-1] * -1)', 'bins'], {}), '(bins[::-1][:-1] * -1, bins)\n', (20601, 20629), True, 'import numpy as np\n'), ((20667, 20743), 'pandas.cut', 'pd.cut', (["self.Combined['STD']"], {'bins': 'self.Combined_STD_bins', 'duplicates': '"""drop"""'}), "(self.Combined['STD'], bins=self.Combined_STD_bins, duplicates='drop')\n", (20673, 20743), True, 'import pandas as pd\n'), ((2816, 2864), 'pandas.DatetimeIndex', 'pd.DatetimeIndex', (["self.CA_PoliceKillings['date']"], {}), "(self.CA_PoliceKillings['date'])\n", (2832, 2864), True, 'import pandas as pd\n'), ((7597, 7674), 'pandas.DatetimeIndex', 'pd.DatetimeIndex', (["self.US_PoliceKillings['Date of Incident (month/day/year)']"], {}), "(self.US_PoliceKillings['Date of Incident (month/day/year)'])\n", (7613, 7674), True, 'import pandas as pd\n'), ((18549, 18654), 'pandas.cut', 'pd.cut', (['self.CA[column]'], {'bins': 'self.Manual_Bins', 'labels': 'labels', 'include_lowest': '(True)', 'duplicates': '"""drop"""'}), "(self.CA[column], bins=self.Manual_Bins, labels=labels,\n include_lowest=True, duplicates='drop')\n", (18555, 18654), True, 'import pandas as pd\n'), ((18860, 18965), 'pandas.cut', 'pd.cut', (['self.US[column]'], {'bins': 'self.Manual_Bins', 'labels': 'labels', 'include_lowest': '(True)', 'duplicates': '"""drop"""'}), "(self.US[column], bins=self.Manual_Bins, labels=labels,\n include_lowest=True, duplicates='drop')\n", (18866, 18965), True, 'import pandas as pd\n'), ((19177, 19288), 'pandas.cut', 'pd.cut', (['self.Combined[column]'], {'bins': 'self.Manual_Bins', 'labels': 'labels', 'include_lowest': '(True)', 'duplicates': '"""drop"""'}), "(self.Combined[column], bins=self.Manual_Bins, labels=labels,\n include_lowest=True, duplicates='drop')\n", (19183, 19288), True, 'import pandas as pd\n'), ((5313, 5372), 'geopandas.read_file', 'gpd.read_file', (['"""Inputs/Canadian_Census_Boundaries_2016.shp"""'], {}), "('Inputs/Canadian_Census_Boundaries_2016.shp')\n", (5326, 5372), True, 'import geopandas as gpd\n'), ((10292, 10340), 'geopandas.read_file', 'gpd.read_file', (['"""Inputs/cb_2018_us_state_20m.shp"""'], {}), "('Inputs/cb_2018_us_state_20m.shp')\n", (10305, 10340), True, 'import geopandas as gpd\n')]
import numpy as np def rnn_step_forward(x, prev_h, Wx, Wh, b): """ Inputs: - x: Input data for this timestep, of shape (N, D). - prev_h: Hidden state from previous timestep, of shape (N, H) - Wx: Weight matrix for input-to-hidden connections, of shape (D, H) - Wh: Weight matrix for hidden-to-hidden connections, of shape (H, H) - b: Biases of shape (H,) Returns a tuple of: - next_h: Next hidden state, of shape (N, H) - cache: Tuple of values needed for the backward pass. """ next_h, cache = None, None forward = x.dot(Wx) + prev_h.dot(Wh) + b # squeeze with tanh next_h = np.tanh(forward) cache = x, prev_h, Wx, Wh, forward return next_h, cache def rnn_step_backward(dnext_h, cache): """ Inputs: - dnext_h: Gradient of loss with respect to next hidden state, of shape (N, H) - cache: Cache object from the forward pass Returns a tuple of: - dx: Gradients of input data, of shape (N, D) - dprev_h: Gradients of previous hidden state, of shape (N, H) - dWx: Gradients of input-to-hidden weights, of shape (D, H) - dWh: Gradients of hidden-to-hidden weights, of shape (H, H) - db: Gradients of bias vector, of shape (H,) """ dx, dprev_h, dWx, dWh, db = None, None, None, None, None x, prev_h, Wx, Wh, forward = cache # derivative(tanh x) = 1 - tanh^2 x dforward = (1 - np.tanh(forward)**2) * dnext_h dx = dforward.dot(Wx.T) dprev_h = dforward.dot(Wh.T) dWx = x.T.dot(dforward) dWh = prev_h.T.dot(dforward) db = np.sum(dforward, axis=0) return dx, dprev_h, dWx, dWh, db def rnn_forward(x, h0, Wx, Wh, b): """ Inputs: - x: Input data for the entire timeseries, of shape (N, T, D). - h0: Initial hidden state, of shape (N, H) - Wx: Weight matrix for input-to-hidden connections, of shape (D, H) - Wh: Weight matrix for hidden-to-hidden connections, of shape (H, H) - b: Biases of shape (H,) Returns a tuple of: - h: Hidden states for the entire timeseries, of shape (N, T, H). - cache: Values needed in the backward pass """ h, cache = None, None N, T = x.shape[0], x.shape[1] H = h0.shape[1] cache = [] h = np.zeros((N, T, H)) prev_h = h0 for i in range(T): prev_h, cache_current = rnn_step_forward(x[:,i,:], prev_h, Wx, Wh, b) h[:, i, :] = prev_h # cache_current[-1] -> forward value in each step cache.append(cache_current) return h, cache def rnn_backward(dh, cache): """ Inputs: - dh: Upstream gradients of all hidden states, of shape (N, T, H). Returns a tuple of: - dx: Gradient of inputs, of shape (N, T, D) - dh0: Gradient of initial hidden state, of shape (N, H) - dWx: Gradient of input-to-hidden weights, of shape (D, H) - dWh: Gradient of hidden-to-hidden weights, of shape (H, H) - db: Gradient of biases, of shape (H,) """ dx, dh0, dWx, dWh, db = None, None, None, None, None N, T, H = dh.shape D = cache[0][0].shape[1] dWx = np.zeros((D, H)) dWh = np.zeros((H, H)) dx = np.zeros((N, T, D)) db = np.zeros(H) # Weights are added in each gradient calculation because the same weights are # applied on each input. dh_prev = np.zeros((N, H)) for i in reversed(range(T)): dh_current = dh[:,i,:] + dh_prev dx[:, i, :], dh_prev, dWx_current, dWh_current, db_current = \ rnn_step_backward(dh_current, cache[i]) dWx += dWx_current dWh += dWh_current db += db_current dh0 = dh_prev return dx, dh0, dWx, dWh, db
[ "numpy.zeros", "numpy.sum", "numpy.tanh" ]
[((639, 655), 'numpy.tanh', 'np.tanh', (['forward'], {}), '(forward)\n', (646, 655), True, 'import numpy as np\n'), ((1567, 1591), 'numpy.sum', 'np.sum', (['dforward'], {'axis': '(0)'}), '(dforward, axis=0)\n', (1573, 1591), True, 'import numpy as np\n'), ((2233, 2252), 'numpy.zeros', 'np.zeros', (['(N, T, H)'], {}), '((N, T, H))\n', (2241, 2252), True, 'import numpy as np\n'), ((3070, 3086), 'numpy.zeros', 'np.zeros', (['(D, H)'], {}), '((D, H))\n', (3078, 3086), True, 'import numpy as np\n'), ((3097, 3113), 'numpy.zeros', 'np.zeros', (['(H, H)'], {}), '((H, H))\n', (3105, 3113), True, 'import numpy as np\n'), ((3123, 3142), 'numpy.zeros', 'np.zeros', (['(N, T, D)'], {}), '((N, T, D))\n', (3131, 3142), True, 'import numpy as np\n'), ((3152, 3163), 'numpy.zeros', 'np.zeros', (['H'], {}), '(H)\n', (3160, 3163), True, 'import numpy as np\n'), ((3290, 3306), 'numpy.zeros', 'np.zeros', (['(N, H)'], {}), '((N, H))\n', (3298, 3306), True, 'import numpy as np\n'), ((1405, 1421), 'numpy.tanh', 'np.tanh', (['forward'], {}), '(forward)\n', (1412, 1421), True, 'import numpy as np\n')]
import logging import numpy as np from pyrieef.geometry.workspace import Circle, Box, Workspace # temporary importing until complication of install is resolve import os import sys _path_file = os.path.dirname(os.path.realpath(__file__)) sys.path.append(os.path.join(_path_file, "../../../bewego")) from pybewego import PlanarOptimizer from pybewego.workspace_viewer_server import WorkspaceViewerServer class TrajectoryConstraintObjective: logger = logging.getLogger(__name__) def __init__(self, **kwargs): self.verbose = kwargs.get('verbose', False) self.T = kwargs.get('T', 0) # time steps self.dt = kwargs.get('dt', 0.1) # sample rate self.n = kwargs.get('n', 2) # set parameters self.set_parameters(**kwargs) self.objective = None # ipopt options self.ipopt_options = { 'tol': kwargs.get('tol', 9e-3), 'acceptable_tol': kwargs.get('tol', 1e-2), 'acceptable_constr_viol_tol': kwargs.get('acceptable_constr_viol_tol', 5e-1), 'constr_viol_tol': kwargs.get('constr_viol_tol', 2e-2), 'max_iter': kwargs.get('max_iter', 200), # 'bound_relax_factor': kwargs.get('bound_relax_factor', 0), 'obj_scaling_factor': kwargs.get('obj_scaling_factor', 1e+2) } # viewer self.enable_viewer = kwargs.get('enable_viewer', False) self.delay_viewer = kwargs.get('delay_viewer', 200) def set_parameters(self, **kwargs): self.workspace = kwargs.get('workspace', None) self.trajectory = kwargs.get('trajectory', None) if self.trajectory is not None: self._q_init = self.trajectory.initial_configuration() self._q_goal = self.trajectory.final_configuration() self.T = self.trajectory.T() self.n = self.trajectory.n() self.waypoints = kwargs.get('waypoints', None) self.waypoint_manifolds = kwargs.get('waypoint_manifolds', None) self.goal_manifold = kwargs.get('goal_manifold', None) self.s_velocity_norm = kwargs.get('s_velocity_norm', 0) self.s_acceleration_norm = kwargs.get('s_acceleration_norm', 20) self.s_obstacles = kwargs.get('s_obstacles', 1e+3) self.s_obstacle_alpha = kwargs.get('s_obstacle_alpha', 7) self.s_obstacle_gamma = kwargs.get('s_obstacle_gamma', 60) self.s_obstacle_margin = kwargs.get('s_obstacle_margin', 0.) self.s_obstacle_constraint = kwargs.get('s_obstacle_constraint', 1) self.with_smooth_obstacle_constraint = kwargs.get('with_smooth_obstacle_constraint', True) self.s_terminal_potential = kwargs.get('s_terminal_potential', 1e+4) self.with_goal_constraint = kwargs.get('with_goal_constraint', True) self.with_goal_manifold = kwargs.get('with_goal_manifold', True) self.s_waypoint_constraint = kwargs.get('s_waypoint_constraint', 1e+4) self.with_waypoint_constraint = kwargs.get('with_waypoint_constraint', True) def set_problem(self, **kwargs): self.set_parameters(**kwargs) if self.workspace is None: TrajectoryConstraintObjective.logger.error('Workspace is not defined! Cannot set optimization problem.') return if self.trajectory is None: TrajectoryConstraintObjective.logger.error('Init trajectory is not defined! Cannot set optimization problem.') return self.problem = PlanarOptimizer(self.T, self.dt, self.workspace.box.box_extent()) # Add workspace obstacles for o in self.workspace.obstacles: if isinstance(o, Circle): self.problem.add_sphere(o.origin, o.radius) elif isinstance(o, Box): self.problem.add_box(o.origin, o.dim) else: TrajectoryConstraintObjective.logger.warn('Shape {} not supported by bewego'.format(type(o))) # terms if self.s_velocity_norm > 0: self.problem.add_smoothness_terms(1, self.s_velocity_norm) if self.s_acceleration_norm > 0: self.problem.add_smoothness_terms(2, self.s_acceleration_norm) if self.s_obstacles > 0: self.problem.add_obstacle_terms( self.s_obstacles, self.s_obstacle_alpha, self.s_obstacle_margin) if self.s_terminal_potential > 0: if self.with_goal_constraint: if self.with_goal_manifold: self.problem.add_goal_manifold_constraint(self.goal_manifold.origin, self.goal_manifold.radius, self.s_terminal_potential) else: self.problem.add_goal_constraint(self.q_goal, self.s_terminal_potential) else: self.problem.add_terminal_potential_terms(self.q_goal, self.s_terminal_potential) if self.s_waypoint_constraint > 0: if self.waypoints is not None: # waypoints take precedent for i in range(1, len(self.waypoints) - 1): if self.with_waypoint_constraint: self.problem.add_waypoint_constraint(*self.waypoints[i], self.s_waypoint_constraint) else: self.problem.add_waypoint_terms(*self.waypoints[i], self.s_waypoint_constraint) elif self.waypoint_manifolds is not None: for i in range(len(self.waypoint_manifolds) - 1): self.problem.add_waypoint_manifold_constraint(self.waypoint_manifolds[i][0].origin, self.waypoint_manifolds[i][1], self.waypoint_manifolds[i][0].radius, self.s_waypoint_constraint) if self.s_obstacle_constraint > 0: if self.with_smooth_obstacle_constraint: self.problem.add_smooth_keypoints_surface_constraints(self.s_obstacle_margin, self.s_obstacle_gamma, self.s_obstacle_constraint) else: self.problem.add_keypoints_surface_constraints(self.s_obstacle_margin, self.s_obstacle_constraint) self.objective = self.problem.objective(self.q_init) if self.enable_viewer: self.obstacle_potential = self.problem.obstacle_potential() print(self.obstacle_potential) self.problem.set_trajectory_publisher(False, self.delay_viewer) def cost(self, trajectory=None): ''' Should call set problem first ''' if self.objective is not None: if trajectory is None: trajectory = self.trajectory return self.objective.forward(trajectory.active_segment())[0] else: return 0. def optimize(self, status=None, traj=None, ipopt_options=None): if ipopt_options is None: ipopt_options = self.ipopt_options res = self.problem.optimize( self.trajectory.x(), self.q_goal, ipopt_options ) self.trajectory.active_segment()[:] = res.x if self.verbose: TrajectoryConstraintObjective.logger.info('Gradient norm : %f' % np.linalg.norm(res.jac)) if status is not None: # get out status from multiprocessing status.value = res.success if traj is not None: traj[:] = self.trajectory.x().tolist() return res.success, self.trajectory @property def q_init(self): return self._q_init @q_init.setter def q_init(self, value): self._q_init = value @property def q_goal(self): return self._q_goal @q_goal.setter def q_goal(self, value): self._q_goal = value
[ "numpy.linalg.norm", "os.path.realpath", "os.path.join", "logging.getLogger" ]
[((212, 238), 'os.path.realpath', 'os.path.realpath', (['__file__'], {}), '(__file__)\n', (228, 238), False, 'import os\n'), ((256, 299), 'os.path.join', 'os.path.join', (['_path_file', '"""../../../bewego"""'], {}), "(_path_file, '../../../bewego')\n", (268, 299), False, 'import os\n'), ((457, 484), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (474, 484), False, 'import logging\n'), ((7081, 7104), 'numpy.linalg.norm', 'np.linalg.norm', (['res.jac'], {}), '(res.jac)\n', (7095, 7104), True, 'import numpy as np\n')]
import logging import math import time import typing from collections.abc import Sequence import numpy as np from qtpy.QtCore import QModelIndex, Qt, QVariant, QAbstractListModel from scipy import signal WINDOW_MAPPING = { 'Hann': signal.windows.hann, 'Hamming': signal.windows.hamming, 'Blackman-Harris': signal.windows.blackmanharris, 'Nuttall': signal.windows.nuttall, 'Tukey': signal.windows.tukey, 'Rectangle': signal.windows.boxcar } REAL_WORLD_DATA = 'REALWORLD' # events that listeners have to handle LOAD_MEASUREMENTS = 'LOAD' CLEAR_MEASUREMENTS = 'CLEAR' logger = logging.getLogger('measurement') class MeasurementModel(Sequence): ''' Models a related collection of measurements Propagates events to listeners when the model changes Allows assorted analysis to be performed against those measurements. ''' def __init__(self, display_model, m=None, listeners=None): self.__measurements = m if m is not None else [] self.__listeners = listeners if listeners is not None else [] self.__display_model = display_model self.__display_model.measurementModel = self self.__measurements = [] self.__power_response = None self.__di = None self.table = None super().__init__() def __getitem__(self, i): return self.__measurements[i] def __len__(self): return len(self.__measurements) @property def power_response(self): return self.__power_response @property def di(self): return self.__di def register_listener(self, listener): ''' Registers a listener for changes to measurements. Must provide onMeasurementUpdate methods that take no args and an idx as well as a clear method. :param listener: the listener. ''' self.__listeners.append(listener) def __propagate_event(self, event_type, **kwargs): ''' propagates the specified event to all listeners. :param event_type: the event type. :param kwargs: the event args. ''' for l in self.__listeners: start = time.time() l.on_update(event_type, **kwargs) end = time.time() logger.debug(f"Propagated event: {event_type} to {l} in {round((end - start) * 1000)}ms") def load(self, measurements): ''' Loads measurements. :param measurements: the measurements. ''' if self.table is not None: self.table.beginResetModel() if len(self.__measurements) > 0: self.clear(reset=False) self.__measurements = measurements if self.table is not None: self.table.endResetModel() if len(self.__measurements) > 0: self.__propagate_event(LOAD_MEASUREMENTS) else: self.__propagate_event(CLEAR_MEASUREMENTS) def clear(self, reset=True): ''' Clears the loaded measurements. ''' if self.table is not None and reset: self.table.beginResetModel() self.__measurements = [] if self.table is not None and reset: self.table.endResetModel() self.__propagate_event(CLEAR_MEASUREMENTS) def normalisation_changed(self): ''' flags that the normalisation selection has changed. :param normalised: true if normalised. :param angle: the angle to normalise to. ''' self.__propagate_event(LOAD_MEASUREMENTS) def get_magnitude_data(self): ''' Gets the magnitude data of the specified type from the model. :return: the data (if any) ''' data = [x for x in self.__measurements] if self.__display_model.normalised: target = next( (x for x in data if math.isclose(float(x.h), float(self.__display_model.normalisation_angle))), None) if target: data = [x.normalise(target) for x in data] else: print(f"Unable to normalise {self.__display_model.normalisation_angle}") return data def get_contour_data(self): ''' Generates data for contour plots from the analysed data sets. :param type: the type of data to retrieve. :return: the data as a dict with xyz keys. ''' # convert to a table of xyz coordinates where x = frequencies, y = angles, z = magnitude mag = self.get_magnitude_data() return { 'x': np.array([d.x for d in mag]).flatten(), 'y': np.array([d.h for d in mag]).repeat(mag[0].x.size), 'z': np.array([d.y for d in mag]).flatten() } class Measurement: ''' A single measurement taken in the real world. ''' def __init__(self, name, h=0, v=0, freq=np.array([]), spl=np.array([])): self.__name = name self.__h = h self.__v = v self.__freq = freq self.__spl = spl def mirror(self): return Measurement(self.__name, h=-self.h, v=-self.v, freq=self.freq, spl=self.spl) @property def h(self): return self.__h @property def v(self): return self.__v @property def name(self): return self.__name @property def freq(self): return self.__freq @property def x(self): return self.freq @property def spl(self): return self.__spl @property def y(self): return self.spl @property def display_name(self): ''' :return: the display name of this measurement. ''' return f"{self.name}:H{self.h}V{self.v}" def __repr__(self): return f"{self.__class__.__name__}: {self.display_name}" def normalise(self, target): ''' Normalises the y value against the target y. :param target: the target. :return: a normalised measurement. ''' return Measurement(self.name, h=self.h, v=self.v, freq=self.x, spl=self.y - target.y) class MeasurementListModel(QAbstractListModel): ''' A Qt table model to feed the measurements view. ''' def __init__(self, model, parent=None): super().__init__(parent=parent) self._measurementModel = model self._measurementModel.table = self def rowCount(self, parent: QModelIndex = ...): return len(self._measurementModel) def data(self, index: QModelIndex, role: int = ...) -> typing.Any: if not index.isValid(): return QVariant() elif role != Qt.DisplayRole: return QVariant() else: return QVariant(self._measurementModel[index.row()]._name)
[ "qtpy.QtCore.QVariant", "numpy.array", "logging.getLogger", "time.time" ]
[((603, 635), 'logging.getLogger', 'logging.getLogger', (['"""measurement"""'], {}), "('measurement')\n", (620, 635), False, 'import logging\n'), ((4858, 4870), 'numpy.array', 'np.array', (['[]'], {}), '([])\n', (4866, 4870), True, 'import numpy as np\n'), ((4876, 4888), 'numpy.array', 'np.array', (['[]'], {}), '([])\n', (4884, 4888), True, 'import numpy as np\n'), ((2163, 2174), 'time.time', 'time.time', ([], {}), '()\n', (2172, 2174), False, 'import time\n'), ((2239, 2250), 'time.time', 'time.time', ([], {}), '()\n', (2248, 2250), False, 'import time\n'), ((6584, 6594), 'qtpy.QtCore.QVariant', 'QVariant', ([], {}), '()\n', (6592, 6594), False, 'from qtpy.QtCore import QModelIndex, Qt, QVariant, QAbstractListModel\n'), ((6651, 6661), 'qtpy.QtCore.QVariant', 'QVariant', ([], {}), '()\n', (6659, 6661), False, 'from qtpy.QtCore import QModelIndex, Qt, QVariant, QAbstractListModel\n'), ((4551, 4579), 'numpy.array', 'np.array', (['[d.x for d in mag]'], {}), '([d.x for d in mag])\n', (4559, 4579), True, 'import numpy as np\n'), ((4608, 4636), 'numpy.array', 'np.array', (['[d.h for d in mag]'], {}), '([d.h for d in mag])\n', (4616, 4636), True, 'import numpy as np\n'), ((4677, 4705), 'numpy.array', 'np.array', (['[d.y for d in mag]'], {}), '([d.y for d in mag])\n', (4685, 4705), True, 'import numpy as np\n')]
import torch from tqdm import tqdm import os from tensorboardX import SummaryWriter import numpy as np from config import coordinates_cat, proposalN, set, vis_num from utils.cal_iou import calculate_iou from utils.vis import image_with_boxes def eval(model, testloader, criterion, status, save_path, epoch): model.eval() print('Evaluating') raw_loss_sum = 0 local_loss_sum = 0 windowscls_loss_sum = 0 total_loss_sum = 0 iou_corrects = 0 raw_correct = 0 local_correct = 0 with torch.no_grad(): for i, data in enumerate(tqdm(testloader)): if set == 'CUB': images, labels, boxes, scale = data else: images, labels = data images = images.cuda() labels = labels.cuda() proposalN_windows_score,proposalN_windows_logits, indices, \ window_scores, coordinates, raw_logits, local_logits, local_imgs = model(images, epoch, i, status) raw_loss = criterion(raw_logits, labels) local_loss = criterion(local_logits, labels) windowscls_loss = criterion(proposalN_windows_logits, labels.unsqueeze(1).repeat(1, proposalN).view(-1)) total_loss = raw_loss + local_loss + windowscls_loss raw_loss_sum += raw_loss.item() local_loss_sum += local_loss.item() windowscls_loss_sum += windowscls_loss.item() total_loss_sum += total_loss.item() if set == 'CUB': # computer resized coordinates of boxes boxes_coor = boxes.float() resized_boxes = torch.cat([(boxes_coor[:,0] * scale[:, 0]).unsqueeze(1) ,(boxes_coor[:,1] * scale[:, 1]).unsqueeze(1), (boxes_coor[:,2] * scale[:, 0]).unsqueeze(1), (boxes_coor[:,3] * scale[:, 1]).unsqueeze(1)], dim=1) resized_coor = torch.cat([resized_boxes[:,0].unsqueeze(1) ,resized_boxes[:,1].unsqueeze(1), (resized_boxes[:,0] + resized_boxes[:,2]).unsqueeze(1), (resized_boxes[:,1]+resized_boxes[:,3]).unsqueeze(1)], dim=1).round().int() iou = calculate_iou(coordinates.cpu().numpy(), resized_coor.numpy()) iou_corrects += np.sum(iou >= 0.5) # correct num # raw pred = raw_logits.max(1, keepdim=True)[1] raw_correct += pred.eq(labels.view_as(pred)).sum().item() # local pred = local_logits.max(1, keepdim=True)[1] local_correct += pred.eq(labels.view_as(pred)).sum().item() # raw branch tensorboard if i == 0: if set == 'CUB': box_coor = resized_coor[:vis_num].numpy() pred_coor = coordinates[:vis_num].cpu().numpy() with SummaryWriter(log_dir=os.path.join(save_path, 'log'), comment=status + 'raw') as writer: cat_imgs = [] for j, coor in enumerate(box_coor): img = image_with_boxes(images[j], [coor]) img = image_with_boxes(img, [pred_coor[j]], color=(0, 255, 0)) cat_imgs.append(img) cat_imgs = np.concatenate(cat_imgs, axis=1) writer.add_images(status + '/' + 'raw image with boxes', cat_imgs, epoch, dataformats='HWC') # object branch tensorboard if i == 0: indices_ndarray = indices[:vis_num,:proposalN].cpu().numpy() with SummaryWriter(log_dir=os.path.join(save_path, 'log'), comment=status + 'object') as writer: cat_imgs = [] for j, indice_ndarray in enumerate(indices_ndarray): img = image_with_boxes(local_imgs[j], coordinates_cat[indice_ndarray]) cat_imgs.append(img) cat_imgs = np.concatenate(cat_imgs, axis=1) writer.add_images(status + '/' + 'object image with windows', cat_imgs, epoch, dataformats='HWC') # if status == 'train': # if i >= 2 : # break raw_loss_avg = raw_loss_sum / (i+1) local_loss_avg = local_loss_sum / (i+1) windowscls_loss_avg = windowscls_loss_sum / (i+1) total_loss_avg = total_loss_sum / (i+1) raw_accuracy = raw_correct / len(testloader.dataset) local_accuracy = local_correct / len(testloader.dataset) return raw_loss_avg, windowscls_loss_avg, total_loss_avg, raw_accuracy, local_accuracy, \ local_loss_avg
[ "tqdm.tqdm", "utils.vis.image_with_boxes", "numpy.sum", "torch.no_grad", "os.path.join", "numpy.concatenate" ]
[((519, 534), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (532, 534), False, 'import torch\n'), ((569, 585), 'tqdm.tqdm', 'tqdm', (['testloader'], {}), '(testloader)\n', (573, 585), False, 'from tqdm import tqdm\n'), ((2323, 2341), 'numpy.sum', 'np.sum', (['(iou >= 0.5)'], {}), '(iou >= 0.5)\n', (2329, 2341), True, 'import numpy as np\n'), ((4022, 4054), 'numpy.concatenate', 'np.concatenate', (['cat_imgs'], {'axis': '(1)'}), '(cat_imgs, axis=1)\n', (4036, 4054), True, 'import numpy as np\n'), ((3340, 3372), 'numpy.concatenate', 'np.concatenate', (['cat_imgs'], {'axis': '(1)'}), '(cat_imgs, axis=1)\n', (3354, 3372), True, 'import numpy as np\n'), ((3881, 3945), 'utils.vis.image_with_boxes', 'image_with_boxes', (['local_imgs[j]', 'coordinates_cat[indice_ndarray]'], {}), '(local_imgs[j], coordinates_cat[indice_ndarray])\n', (3897, 3945), False, 'from utils.vis import image_with_boxes\n'), ((3129, 3164), 'utils.vis.image_with_boxes', 'image_with_boxes', (['images[j]', '[coor]'], {}), '(images[j], [coor])\n', (3145, 3164), False, 'from utils.vis import image_with_boxes\n'), ((3199, 3255), 'utils.vis.image_with_boxes', 'image_with_boxes', (['img', '[pred_coor[j]]'], {'color': '(0, 255, 0)'}), '(img, [pred_coor[j]], color=(0, 255, 0))\n', (3215, 3255), False, 'from utils.vis import image_with_boxes\n'), ((3674, 3704), 'os.path.join', 'os.path.join', (['save_path', '"""log"""'], {}), "(save_path, 'log')\n", (3686, 3704), False, 'import os\n'), ((2930, 2960), 'os.path.join', 'os.path.join', (['save_path', '"""log"""'], {}), "(save_path, 'log')\n", (2942, 2960), False, 'import os\n')]
import os import netCDF4 as nc4 import numpy as np import matplotlib.pyplot as plt import numpy.ma as ma import glob import xarray as xr import collections def make_yearly_cdf(syear,eyear, sat, dataloc, odir, evars): ''' PURPOSE: This program takes monthly Lbin files and turns them into yearly cumulative distributions as a function of hemisphere, satellite direction, L, lon, and Kp INPUTS: :param: syear (int)- The start year (YYYY) to create yearly cdfs for :param: eyear (int)- The end year (YYYY) to create yearly cdfs for :param: sat (str)- The satellite to create yearly cdfs for :param: odir (str)- The directory for putting the output files :param: evars list(str)- A list of the variables to create cdfs for NOTE!!! This is currently only set up to work well with the default variables. It will need to be updated in the future to work with any variable by automatically defining the cdfs bins from the data. Right now the bins are hard coded with what works best for particle fluxes, mag field, and pitch angles. OUTPUTS: netcdf files called odir/sat/poes_cdf_sat_YYYY.nc and two types of plots The output files contain the cdf percentiles for each binned variable, the value for each percentile, and the total counts in each bin. The cdfs are accumulated by hemisphere (N==0, S==1), satellite direction (Northward = 0 Soutward =1), L (0 to 8 in .25 increments), longitude(0 to 360 in 10 degree bins) and Kp (0-10). For example data['mep_ele_tel90_e1][0,0,8,0,1,:] would give the percentile values for fluxbins (0 to 8 in .1 increments) in the Northern hemisphere when the satellite is moving northward at L=3-3.25, lon =0-10 and Kp=1-2. data['mep_ele_tel90_e1_sar][0,0,8,0,1,:] would give the flux values for percentile bin (0 to 1 in .1 increments) in the Northern hemisphere when the satellite is moving northward at L=3-3.25, lon =0-10 and Kp=1-2. data['mep_ele_tel90_e1_n][0,0,8,0,1] would give the number of values (0 to 1 in .1 increments) in the Northern hemisphere when the satellite is moving northward between L=3-3.25, lon =0-10 and Kp=1-2. ''' #syear = # year to start with #eyear = 2014 # year to end with #sat = 'm02' # satellite to user #m02,m01,n15,n18,n19 # NOTE on zeros # When creating the cdfs we are working with the log flux so 0's would # normally be thrown out. Instead we set it to the half count value which is energy dependent Ge = [100/1.24,100/1.44,100/.75,100/.55] Gp = [100 / 42.95, 100 / 135.28, 100 / 401.09, 100 / 1128.67, 100/2202.93,100/.41] # Each monthly Lbin netcdf file has data[var][time_med,Lbins] # These variables are standard in the monthly Lbin files. They are required for this code loc_vars = ['time', 'L_IGRF', 'lat', 'lon', 'MLT','NS','Kp*10'] # Add the variables to be processed # It will be up to the user to make sure the vars they want are actually in the Lbin data files allvars = loc_vars + list(evars) # These variables are to store the total number of points in each bin nvars = list() for var in evars: nvars.append(var+'_n') # These variables will hold the flux or value as a function of percentile from 0-1 svars = list() for var in evars: svars.append(var+'_sar') # This is going to be for the output flux as a function of percentile # svars = ['mep_ele_tel90_flux_e1_sar','mep_ele_tel90_flux_e2_sar', # 'mep_ele_tel90_flux_e3_sar','mep_ele_tel90_flux_e4_sar','Btot_sat_sar','meped_alpha_90_sat_sar'] lonbins = np.arange(0, 360, 10) # These are the longitude bins Lbins = np.arange(1, 8.25, .25) # These are the Lbins binvals = np.arange(0, 8.1,.1) # These are the log electron flux bins Bbins = np.arange(16700,44500,100) # These are the bins for the magnetic field (if needed) pbins = np.arange(0,90,1) # These are the bins for the pitch angles (if needed) percentiles = np.arange(0,1.01,.01) # These are the percentile bins Kp = np.arange(0,10) # These are the Kp bins # Directory for storing the cdf info files cdf_direc = odir + '/'+sat +'/' #cdf_direc = '/Users/janet/PycharmProjects/SHELLS/cdfdataV5/'+sat+'/' # Check if the output directory exists and create it if not if not os.path.isdir(odir): os.mkdir(odir) # Now make the sat directory if it doesn't exist if not os.path.isdir(cdf_direc): os.mkdir(cdf_direc) while syear<=eyear: # This is the netcdf file for storing the cdf info fn = cdf_direc+ 'poes_cdf_'+sat + '_'+ str(syear).zfill(4) +'.nc' cdf_data = nc4.Dataset(fn, 'w', clobber =True) cdf_data.createDimension('hemi', 2) # North or south hemisphere cdf_data.createDimension('NS', 2) # North or south direction of sat(also corresponds to MLT) cdf_data.createDimension('Lbin', len(Lbins)) cdf_data.createDimension('lonbin', len(lonbins)) cdf_data.createDimension('fluxbins', len(binvals)) cdf_data.createDimension('percentiles', len(percentiles)) # Create the magnetic field bins if needed # This should work for any B field values if any([x.find('B')>-1 for x in evars]): cdf_data.createDimension('Bbins', len(Bbins)) cdf_data.createVariable('Bbins', np.float64, ('Bbins')) cdf_data.variables['Bbins'][:] = Bbins # Create the pitch angle bins if any([x.find('meped_alpha')>-1 for x in evars]): cdf_data.createDimension('pbins', len(pbins)) cdf_data.createVariable('pbins', np.float64, ('pbins')) cdf_data.variables['pbins'][:] = pbins # Kp is required # To do : change this so that other solar wind params could be used cdf_data.createDimension('Kp', len(Kp)) cdf_data.createVariable('Kp', np.float64, ('Kp')) cdf_data.variables['Kp'][:] = Kp cdf_data.createVariable('Lbin', np.float64, ('Lbin')) cdf_data.createVariable('hemi', np.int, ('hemi')) cdf_data.createVariable('NS', np.int, ('NS')) cdf_data.createVariable('lonbin', np.float64, ('lonbin')) cdf_data.createVariable('fluxbins', np.float64, ('fluxbins')) cdf_data.createVariable('percentiles', np.float64, ('percentiles')) # This is the percentile for each electron fluxbin or other data for var in evars: if var.find('ele')>-1: cdf_data.createVariable(var, np.float64, ('hemi','NS','Lbin','lonbin','Kp','fluxbins')) cdf_data.variables[var][:, :, :, :, :, :] = 0 if var.find('B')>-1: cdf_data.createVariable(var, np.float64, ('hemi', 'NS', 'Lbin', 'lonbin', 'Kp', 'Bbins')) if var.find('alpha')>-1: cdf_data.createVariable(var, np.float64, ('hemi', 'NS', 'Lbin', 'lonbin', 'Kp', 'pbins')) # These are the cdfs for the total B # This is the percentile for each Bbin # for var in Bvars: # cdf_data.createVariable(var, np.float64, ('hemi','NS','Lbin','lonbin','Kp','Bbins')) # This is the cf for the pitchangle #for var in pvars: # cdf_data.createVariable(var, np.float64, ('hemi','NS','Lbin','lonbin','Kp','pbins')) # This is the flux for each percentile bin # It's the same for the electron flux and B for var in svars: cdf_data.createVariable(var, np.float64, ('hemi','NS','Lbin','lonbin','Kp','percentiles')) cdf_data.variables[var][:, :, :, :, :,:] = 0 # this is number of points in each bin for var in nvars: cdf_data.createVariable(var, np.float64, ('hemi','NS','Lbin','lonbin','Kp')) cdf_data.variables[var][:, :, :, :, :] = 0 # number in each bin cdf_data.variables['Lbin'][:] = Lbins cdf_data.variables['hemi'][:] = [0,1] cdf_data.variables['NS'][:] = [0, 1] cdf_data.variables['lonbin'][:] = lonbins cdf_data.variables['fluxbins'][:] = binvals cdf_data.variables['percentiles'][:] = percentiles # This is for making a plot of the median values in the end allmeds = {} meds = np.zeros((2,2,len(Lbins),len(lonbins),len(Kp)),dtype = float) # Get all the sat data for a year Ldirec = dataloc+'/'+str(syear).zfill(4) +'/' files = glob.glob(Ldirec + '*'+sat+'*.nc') files.sort() alldat = xr.open_mfdataset(files) # make a cdf for each hemi, direc (equates to MLT), L, lon, Kp # Add B and pitch angle to evars #evars.append(Bvars[0]) #evars.append(pvars[0]) for var in np.arange(0,len(evars)): # Step through each L for L in np.arange(0, len(Lbins) ): edat = (alldat[evars[var]][:, L].values) # data value for one L # If it is a flux value then take the log10 if evars[var].find('flux')>-1: test_inds = np.where(edat==0)[0] #if len(test_inds)>0: # print(test_inds) # Check if its protons or eclectrons if evars[var].find('ele')>-1: # Find the energy enum = int(evars[var][-1]) edat[edat==0]= .5*Ge[enum-1] elif evars[var].find('pro')>-1: enum = int(evars[var][-1]) edat[edat==0]= .5*Gp[enum-1] fluxdat = np.log10(edat) elif evars[var].find('cps')>-1: edat[edat == 0] =.5 fluxdat = np.log10(edat) else: fluxdat = edat NSdat = alldat['NS'][:, L].values # Why are there lat values that are NaN? latdat = alldat['lat'][:, L].values latdat[latdat >=0] = 0 # Northern hemi latdat[latdat < 0] = 1 # Southern hemi londat = np.floor(alldat['lon'][:, L]/10) # Round Kp to the nearest whole number Kpdat1 = alldat['Kp*10'][:].values # Kpdat = np.floor(Kpdat1/10) # Create indices out of lat, lon, NS, Kp # This is faster than looping through each index indtest2 = (londat * 10000 + Kpdat * 100+ 10 * latdat + NSdat).__array__() # Get all the uniqe indeces inds, counts = np.unique(indtest2[~np.isnan(indtest2)], return_counts=True) result = collections.defaultdict(list) for val, idx in zip(fluxdat, indtest2): if ((~np.isnan(val)) & (~np.isinf(val))): result[idx].append(val) for idx in inds: temp = np.array(result[idx]) #temp2 = temp[(~np.isnan(temp)) & (~np.isinf(temp))] # Get rid of fluxes <.01? data_sorted = np.sort(temp) n = len(temp) if len(temp)>1: p = 1. * np.arange(len(temp)) / (len(temp) - 1) # Interpolate the values to the actual bin values # Everything that is not mag field, or pitch angle is assumed to be flux if evars[var].find('B') >-1: per = np.interp(Bbins, data_sorted, p) elif evars[var].find('alpha') >-1 : per = np.interp(pbins, data_sorted, p) else: per = np.interp(binvals,data_sorted,p) # percentiles interpoalted to binvals (0,.1, ...8) sar = np.interp(percentiles,p,data_sorted) # fluxes interpolated to percentiles (0,.01,...1) else: # If there are no values in the L,lat,lon,Kp bin then set it to 0 if evars[var].find('B') >-1: per = 0*Bbins elif evars[var].find('alpha') >-1: per = 0*pbins else: per = 0*binvals sar =0*percentiles n = 0 #plt.subplot(2,1,1) #plt.plot(data_sorted,p) #plt.plot(binvals, per) #plt.subplot(2,1,2) #plt.plot(p,data_sorted) #plt.plot(percentiles, sar) #print('Plotting') # Get the indices back lonv = np.floor(idx/10000) Kpv = np.floor((idx - lonv*10000)/100) latv = np.floor((idx - lonv*10000 -Kpv*100)/10) NSv = np.floor(idx -lonv*10000 -Kpv*100 - latv*10) # There are some longitudes that equal exactly 360 that should b 0 # It only happens at one point if lonv==36: lonv=0 #print(lonv,Kpv, latv, NSv,idx ) cdf_data.variables[evars[var]][latv, NSv, L, lonv, Kpv, :] = per # percentiles for fluxbins #cdf_data.variables[evars2[var]][latv, NSv, L, lonv, Kpv, :] = per*n cdf_data.variables[nvars[var]][latv, NSv, L, lonv, Kpv] = n # number in each bin cdf_data.variables[svars[var]][latv, NSv, L, lonv, Kpv, :] = sar # flux for percentiles # median value for plotting later meds[int(latv), int(NSv), int(L), int(lonv),int(Kpv)] = sar[np.where(percentiles==.5)] print(L,syear) allmeds[var] = meds # Now make a plot of the median for that variable pco=1 vmi = 1 vma = 5.5 if evars[var].find('B') >-1: vmi = Bbins[0] vma = Bbins[-1] if evars[var].find('alpha') >-1: vmi = pbins[0] vma = pbins[-1] plt.set_cmap('jet') hemisphere = ['N', 'S'] NS = ['N', 'S'] # Make a plot for each Kp val for Kpval in Kp: pco = 1 plt.figure(int(Kpval)) plt.suptitle(sat+' '+evars[var] + ' '+ str(syear).zfill(4)+' Kp='+str(Kpval)) for hemi in range(0,2): for NSco in range(0,2): # Pitch angles in the southern hemi go from 90 to 135 # and in the northern hemi they go from 45 to 90 if (evars[var].find('alpha') >0) & (NSco==1): vmi = 90 vma = 135 if (evars[var].find('alpha') >0) & (NSco == 0): vmi = 45 vma = 90 plt.subplot(2, 2, pco) plt.title( hemisphere[hemi] +'lat '+ NS[NSco]+'bound') plt.pcolormesh(lonbins, Lbins, ma.masked_less(((meds[hemi,NSco,:,:,int(Kpval)])), -8), vmin=vmi, vmax=vma) if (pco == 1) | (pco == 3): plt.ylabel('L IGRF') if (pco == 3) | (pco == 4): plt.xlabel('E longitude') pco = pco+1 cbar = plt.colorbar() if (evars[var].find('alpha') >0): cbar.ax.set_ylabel('degrees') cbar.ax.tick_params(labelsize='small') #print(Kpval) plt.tight_layout(rect=[0, 0.03, 1, 0.95]) # Save the figure to a file figname = cdf_direc +sat+evars[var]+'_'+str(syear).zfill(4)+'_'+str(Kpval)+'.png' plt.savefig(figname) plt.close() # Make line plots for each L to show the longitude variaion plt.figure(int(Kpval+20)) plt.suptitle(sat+' '+evars[var] + ' '+ str(syear).zfill(4)+' Kp='+str(Kpval)) pco=1 for hemi in range(0,2): for NSco in range(0,2): plt.subplot(2, 2, pco) plt.title( hemisphere[hemi] +'lat '+ NS[NSco] +'bound') for Lbin in np.arange(0,28,4): plt.plot(lonbins, ma.masked_less(meds[hemi,NSco,Lbin,:,int(Kpval)],1),label=Lbin/4+1) plt.ylim(1,vma) if pco==1: plt.legend() pco = pco+1 plt.tight_layout() figname = cdf_direc +sat+evars[var]+'_'+str(syear).zfill(4)+'_'+str(Kpval)+'lines.png' plt.savefig(figname) plt.close() print('MAde plot') cdf_data.close() alldat.close() syear = syear +1 if __name__ == '__main__': import argparse ''' PURPOSE: To create yearly files of the cumulative distribution of data as a function of hemisphere(N/S), sat direction(N,S), L, lon, Kp :param: syear - The start year (format YYYY) :param: eyear - The end year (format YYYY) :param: sataname - satellite name (format m02) :param: dataloc - The location of the L binned data files (default ./Lbindata/) :param: odirec - The directory to put the cdf data (default ./cdfdata/) :param: vars - The variables to make cdfs for (default ['mep_ele_tel90_flux_e1', 'mep_ele_tel90_flux_e2', 'mep_ele_tel90_flux_e3', 'mep_ele_tel90_flux_e4', 'meped_alpha_90_sat','Btot_sat']) USAGE (from command line): python make_yearly_cdf -s 2013 -e 2015 -sat m02 -d /SHELLS/Lbindata -od /SHELLS/cdfdata ''' parser = argparse.ArgumentParser('This creates cdf files') # parser.add_argument('-s', "--syear", help="The Start Year - format YYYY ", required=True, default=None, type=int) parser.add_argument('-e', "--eyear", help="The end year - format YYYY ", required=True, default=None, type=int) parser.add_argument('-sat', "--satname", help="A name of satellite data to get (i.e. -sat n15 or -sat n16 ", type=str, required=True) parser.add_argument('-d', "--dataloc", help="The location of the Lbin data", required=False, default=os.getcwd()+'/Lbindata/') parser.add_argument('-od', "--odirec", help="The output directory of data", required=False, default=os.getcwd() + '/cdfdata/') parser.add_argument('-v', "--vars", help="data variables to use", required=False, default=['mep_ele_tel90_flux_e1', 'mep_ele_tel90_flux_e2', 'mep_ele_tel90_flux_e3', 'mep_ele_tel90_flux_e4', 'meped_alpha_90_sat','Btot_sat'], nargs='+') args = parser.parse_args() x = make_yearly_cdf(args.syear, args.eyear, args.satname, args.dataloc, args.odirec, args.vars)
[ "matplotlib.pyplot.title", "os.mkdir", "argparse.ArgumentParser", "numpy.floor", "numpy.isnan", "collections.defaultdict", "numpy.arange", "glob.glob", "numpy.interp", "matplotlib.pyplot.tight_layout", "netCDF4.Dataset", "matplotlib.pyplot.close", "matplotlib.pyplot.colorbar", "matplotlib....
[((3645, 3666), 'numpy.arange', 'np.arange', (['(0)', '(360)', '(10)'], {}), '(0, 360, 10)\n', (3654, 3666), True, 'import numpy as np\n'), ((3710, 3734), 'numpy.arange', 'np.arange', (['(1)', '(8.25)', '(0.25)'], {}), '(1, 8.25, 0.25)\n', (3719, 3734), True, 'import numpy as np\n'), ((3770, 3792), 'numpy.arange', 'np.arange', (['(0)', '(8.1)', '(0.1)'], {}), '(0, 8.1, 0.1)\n', (3779, 3792), True, 'import numpy as np\n'), ((3842, 3870), 'numpy.arange', 'np.arange', (['(16700)', '(44500)', '(100)'], {}), '(16700, 44500, 100)\n', (3851, 3870), True, 'import numpy as np\n'), ((3937, 3956), 'numpy.arange', 'np.arange', (['(0)', '(90)', '(1)'], {}), '(0, 90, 1)\n', (3946, 3956), True, 'import numpy as np\n'), ((4027, 4051), 'numpy.arange', 'np.arange', (['(0)', '(1.01)', '(0.01)'], {}), '(0, 1.01, 0.01)\n', (4036, 4051), True, 'import numpy as np\n'), ((4090, 4106), 'numpy.arange', 'np.arange', (['(0)', '(10)'], {}), '(0, 10)\n', (4099, 4106), True, 'import numpy as np\n'), ((18209, 18258), 'argparse.ArgumentParser', 'argparse.ArgumentParser', (['"""This creates cdf files"""'], {}), "('This creates cdf files')\n", (18232, 18258), False, 'import argparse\n'), ((4364, 4383), 'os.path.isdir', 'os.path.isdir', (['odir'], {}), '(odir)\n', (4377, 4383), False, 'import os\n'), ((4393, 4407), 'os.mkdir', 'os.mkdir', (['odir'], {}), '(odir)\n', (4401, 4407), False, 'import os\n'), ((4473, 4497), 'os.path.isdir', 'os.path.isdir', (['cdf_direc'], {}), '(cdf_direc)\n', (4486, 4497), False, 'import os\n'), ((4507, 4526), 'os.mkdir', 'os.mkdir', (['cdf_direc'], {}), '(cdf_direc)\n', (4515, 4526), False, 'import os\n'), ((4705, 4739), 'netCDF4.Dataset', 'nc4.Dataset', (['fn', '"""w"""'], {'clobber': '(True)'}), "(fn, 'w', clobber=True)\n", (4716, 4739), True, 'import netCDF4 as nc4\n'), ((8470, 8508), 'glob.glob', 'glob.glob', (["(Ldirec + '*' + sat + '*.nc')"], {}), "(Ldirec + '*' + sat + '*.nc')\n", (8479, 8508), False, 'import glob\n'), ((8543, 8567), 'xarray.open_mfdataset', 'xr.open_mfdataset', (['files'], {}), '(files)\n', (8560, 8567), True, 'import xarray as xr\n'), ((14246, 14265), 'matplotlib.pyplot.set_cmap', 'plt.set_cmap', (['"""jet"""'], {}), "('jet')\n", (14258, 14265), True, 'import matplotlib.pyplot as plt\n'), ((10139, 10173), 'numpy.floor', 'np.floor', (["(alldat['lon'][:, L] / 10)"], {}), "(alldat['lon'][:, L] / 10)\n", (10147, 10173), True, 'import numpy as np\n'), ((10305, 10326), 'numpy.floor', 'np.floor', (['(Kpdat1 / 10)'], {}), '(Kpdat1 / 10)\n', (10313, 10326), True, 'import numpy as np\n'), ((10701, 10730), 'collections.defaultdict', 'collections.defaultdict', (['list'], {}), '(list)\n', (10724, 10730), False, 'import collections\n'), ((15927, 15968), 'matplotlib.pyplot.tight_layout', 'plt.tight_layout', ([], {'rect': '[0, 0.03, 1, 0.95]'}), '(rect=[0, 0.03, 1, 0.95])\n', (15943, 15968), True, 'import matplotlib.pyplot as plt\n'), ((16128, 16148), 'matplotlib.pyplot.savefig', 'plt.savefig', (['figname'], {}), '(figname)\n', (16139, 16148), True, 'import matplotlib.pyplot as plt\n'), ((16165, 16176), 'matplotlib.pyplot.close', 'plt.close', ([], {}), '()\n', (16174, 16176), True, 'import matplotlib.pyplot as plt\n'), ((16960, 16978), 'matplotlib.pyplot.tight_layout', 'plt.tight_layout', ([], {}), '()\n', (16976, 16978), True, 'import matplotlib.pyplot as plt\n'), ((17098, 17118), 'matplotlib.pyplot.savefig', 'plt.savefig', (['figname'], {}), '(figname)\n', (17109, 17118), True, 'import matplotlib.pyplot as plt\n'), ((17135, 17146), 'matplotlib.pyplot.close', 'plt.close', ([], {}), '()\n', (17144, 17146), True, 'import matplotlib.pyplot as plt\n'), ((19031, 19042), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (19040, 19042), False, 'import os\n'), ((19209, 19220), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (19218, 19220), False, 'import os\n'), ((9637, 9651), 'numpy.log10', 'np.log10', (['edat'], {}), '(edat)\n', (9645, 9651), True, 'import numpy as np\n'), ((10959, 10980), 'numpy.array', 'np.array', (['result[idx]'], {}), '(result[idx])\n', (10967, 10980), True, 'import numpy as np\n'), ((11114, 11127), 'numpy.sort', 'np.sort', (['temp'], {}), '(temp)\n', (11121, 11127), True, 'import numpy as np\n'), ((12788, 12809), 'numpy.floor', 'np.floor', (['(idx / 10000)'], {}), '(idx / 10000)\n', (12796, 12809), True, 'import numpy as np\n'), ((12834, 12870), 'numpy.floor', 'np.floor', (['((idx - lonv * 10000) / 100)'], {}), '((idx - lonv * 10000) / 100)\n', (12842, 12870), True, 'import numpy as np\n'), ((12894, 12941), 'numpy.floor', 'np.floor', (['((idx - lonv * 10000 - Kpv * 100) / 10)'], {}), '((idx - lonv * 10000 - Kpv * 100) / 10)\n', (12902, 12941), True, 'import numpy as np\n'), ((12961, 13013), 'numpy.floor', 'np.floor', (['(idx - lonv * 10000 - Kpv * 100 - latv * 10)'], {}), '(idx - lonv * 10000 - Kpv * 100 - latv * 10)\n', (12969, 13013), True, 'import numpy as np\n'), ((9092, 9111), 'numpy.where', 'np.where', (['(edat == 0)'], {}), '(edat == 0)\n', (9100, 9111), True, 'import numpy as np\n'), ((9771, 9785), 'numpy.log10', 'np.log10', (['edat'], {}), '(edat)\n', (9779, 9785), True, 'import numpy as np\n'), ((11869, 11907), 'numpy.interp', 'np.interp', (['percentiles', 'p', 'data_sorted'], {}), '(percentiles, p, data_sorted)\n', (11878, 11907), True, 'import numpy as np\n'), ((13809, 13837), 'numpy.where', 'np.where', (['(percentiles == 0.5)'], {}), '(percentiles == 0.5)\n', (13817, 13837), True, 'import numpy as np\n'), ((15110, 15132), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(2)', '(2)', 'pco'], {}), '(2, 2, pco)\n', (15121, 15132), True, 'import matplotlib.pyplot as plt\n'), ((15157, 15214), 'matplotlib.pyplot.title', 'plt.title', (["(hemisphere[hemi] + 'lat ' + NS[NSco] + 'bound')"], {}), "(hemisphere[hemi] + 'lat ' + NS[NSco] + 'bound')\n", (15166, 15214), True, 'import matplotlib.pyplot as plt\n'), ((15687, 15701), 'matplotlib.pyplot.colorbar', 'plt.colorbar', ([], {}), '()\n', (15699, 15701), True, 'import matplotlib.pyplot as plt\n'), ((16520, 16542), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(2)', '(2)', 'pco'], {}), '(2, 2, pco)\n', (16531, 16542), True, 'import matplotlib.pyplot as plt\n'), ((16567, 16624), 'matplotlib.pyplot.title', 'plt.title', (["(hemisphere[hemi] + 'lat ' + NS[NSco] + 'bound')"], {}), "(hemisphere[hemi] + 'lat ' + NS[NSco] + 'bound')\n", (16576, 16624), True, 'import matplotlib.pyplot as plt\n'), ((16659, 16678), 'numpy.arange', 'np.arange', (['(0)', '(28)', '(4)'], {}), '(0, 28, 4)\n', (16668, 16678), True, 'import numpy as np\n'), ((16816, 16832), 'matplotlib.pyplot.ylim', 'plt.ylim', (['(1)', 'vma'], {}), '(1, vma)\n', (16824, 16832), True, 'import matplotlib.pyplot as plt\n'), ((10634, 10652), 'numpy.isnan', 'np.isnan', (['indtest2'], {}), '(indtest2)\n', (10642, 10652), True, 'import numpy as np\n'), ((10813, 10826), 'numpy.isnan', 'np.isnan', (['val'], {}), '(val)\n', (10821, 10826), True, 'import numpy as np\n'), ((10832, 10845), 'numpy.isinf', 'np.isinf', (['val'], {}), '(val)\n', (10840, 10845), True, 'import numpy as np\n'), ((11530, 11562), 'numpy.interp', 'np.interp', (['Bbins', 'data_sorted', 'p'], {}), '(Bbins, data_sorted, p)\n', (11539, 11562), True, 'import numpy as np\n'), ((15493, 15513), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""L IGRF"""'], {}), "('L IGRF')\n", (15503, 15513), True, 'import matplotlib.pyplot as plt\n'), ((15594, 15619), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""E longitude"""'], {}), "('E longitude')\n", (15604, 15619), True, 'import matplotlib.pyplot as plt\n'), ((16895, 16907), 'matplotlib.pyplot.legend', 'plt.legend', ([], {}), '()\n', (16905, 16907), True, 'import matplotlib.pyplot as plt\n'), ((11657, 11689), 'numpy.interp', 'np.interp', (['pbins', 'data_sorted', 'p'], {}), '(pbins, data_sorted, p)\n', (11666, 11689), True, 'import numpy as np\n'), ((11754, 11788), 'numpy.interp', 'np.interp', (['binvals', 'data_sorted', 'p'], {}), '(binvals, data_sorted, p)\n', (11763, 11788), True, 'import numpy as np\n')]