code stringlengths 31 1.05M | apis list | extract_api stringlengths 97 1.91M |
|---|---|---|
# SPDX-FileCopyrightText: 2021 Division of Intelligent Medical Systems, DKFZ
# SPDX-FileCopyrightText: 2021 <NAME>
# SPDX-License-Identifier: MIT
# FIXME temporary workaround for newest Intel architectures
import os
os.environ["KMP_DUPLICATE_LIB_OK"] = "TRUE"
from simpa.utils.path_manager import PathManager
import numpy as np
import os
import matplotlib.pyplot as plt
from scipy.ndimage import zoom
from simpa.io_handling import load_data_field
from simpa.core.simulation import simulate
from simpa.utils import Tags, Settings, TISSUE_LIBRARY
from simpa import MCXAdapter, ModelBasedVolumeCreationAdapter, \
GaussianNoise
from simpa.core.processing_components.monospectral.iterative_qPAI_algorithm import IterativeqPAI
from simpa.core.device_digital_twins import RSOMExplorerP50
from simpa_tests.manual_tests import ManualIntegrationTestClass
class TestqPAIReconstruction(ManualIntegrationTestClass):
"""
This class applies the iterative qPAI reconstruction algorithm on a simple test volume and
- by visualizing the results - lets the user evaluate if the reconstruction is performed correctly.
This test reconstruction contains a volume creation and an optical simulation.
"""
def setup(self):
"""
Runs a pipeline consisting of volume creation and optical simulation. The resulting hdf5 file of the
simple test volume is saved at SAVE_PATH location defined in the path_config.env file.
"""
self.path_manager = PathManager()
self.VOLUME_TRANSDUCER_DIM_IN_MM = 20
self.VOLUME_PLANAR_DIM_IN_MM = 20
self.VOLUME_HEIGHT_IN_MM = 20
self.SPACING = 0.2
self.RANDOM_SEED = 111
self.VOLUME_NAME = "TestqPAIReconstructionVolume_" + str(self.RANDOM_SEED)
np.random.seed(self.RANDOM_SEED)
# These parameters set the general properties of the simulated volume
self.general_settings = {
Tags.RANDOM_SEED: self.RANDOM_SEED,
Tags.VOLUME_NAME: self.VOLUME_NAME,
Tags.SIMULATION_PATH: self.path_manager.get_hdf5_file_save_path(),
Tags.SPACING_MM: self.SPACING,
Tags.DIM_VOLUME_Z_MM: self.VOLUME_HEIGHT_IN_MM,
Tags.DIM_VOLUME_X_MM: self.VOLUME_TRANSDUCER_DIM_IN_MM,
Tags.DIM_VOLUME_Y_MM: self.VOLUME_PLANAR_DIM_IN_MM,
Tags.WAVELENGTHS: [700]
}
self.settings = Settings(self.general_settings)
self.settings.set_volume_creation_settings({
Tags.SIMULATE_DEFORMED_LAYERS: True,
Tags.STRUCTURES: self.create_example_tissue()
})
self.settings.set_optical_settings({
Tags.OPTICAL_MODEL_NUMBER_PHOTONS: 1e7,
Tags.OPTICAL_MODEL_BINARY_PATH: self.path_manager.get_mcx_binary_path(),
Tags.OPTICAL_MODEL: Tags.OPTICAL_MODEL_MCX,
Tags.ILLUMINATION_TYPE: Tags.ILLUMINATION_TYPE_PENCIL,
Tags.LASER_PULSE_ENERGY_IN_MILLIJOULE: 50,
Tags.MCX_ASSUMED_ANISOTROPY: 0.9
})
self.settings["noise_model"] = {
Tags.NOISE_MEAN: 0.0,
Tags.NOISE_STD: 0.4,
Tags.NOISE_MODE: Tags.NOISE_MODE_ADDITIVE,
Tags.DATA_FIELD: Tags.DATA_FIELD_INITIAL_PRESSURE,
Tags.NOISE_NON_NEGATIVITY_CONSTRAINT: True
}
self.device = RSOMExplorerP50(element_spacing_mm=0.5,
number_elements_x=10,
number_elements_y=10,
device_position_mm=np.asarray([self.settings[Tags.DIM_VOLUME_X_MM]/2,
self.settings[Tags.DIM_VOLUME_Y_MM]/2, 0]))
# run pipeline including volume creation and optical mcx simulation
pipeline = [
ModelBasedVolumeCreationAdapter(self.settings),
MCXAdapter(self.settings),
GaussianNoise(self.settings, "noise_model")
]
simulate(pipeline, self.settings, self.device)
def perform_test(self):
"""
Runs iterative qPAI reconstruction on test volume by accessing the settings dictionaries in a hdf5 file.
"""
# set component settings of the iterative method
# if tags are not defined the default is chosen for reconstruction
component_settings = {
Tags.DOWNSCALE_FACTOR: 0.76,
Tags.ITERATIVE_RECONSTRUCTION_CONSTANT_REGULARIZATION: False,
Tags.ITERATIVE_RECONSTRUCTION_MAX_ITERATION_NUMBER: 10,
# for testing, we are interested in all intermediate absorption updates
Tags.ITERATIVE_RECONSTRUCTION_SAVE_INTERMEDIATE_RESULTS: True,
Tags.ITERATIVE_RECONSTRUCTION_STOPPING_LEVEL: 1e-5
}
self.settings["iterative_qpai_reconstruction"] = component_settings
self.wavelength = self.settings[Tags.WAVELENGTH]
absorption_gt = load_data_field(self.settings[Tags.SIMPA_OUTPUT_PATH], Tags.DATA_FIELD_ABSORPTION_PER_CM,
self.wavelength)
# if the initial pressure is resampled the ground truth has to be resampled to allow for comparison
if Tags.DOWNSCALE_FACTOR in component_settings:
self.absorption_gt = zoom(absorption_gt, component_settings[Tags.DOWNSCALE_FACTOR],
order=1, mode="nearest")
else:
self.absorption_gt = zoom(absorption_gt, 0.73, order=1, mode="nearest") # the default scale is 0.73
# run the qPAI reconstruction
IterativeqPAI(self.settings, "iterative_qpai_reconstruction").run(self.device)
# get last iteration result (3-d)
self.hdf5_path = self.path_manager.get_hdf5_file_save_path() + "/" + self.VOLUME_NAME + ".hdf5"
self.reconstructed_absorption = load_data_field(self.hdf5_path, Tags.ITERATIVE_qPAI_RESULT, self.wavelength)
# get reconstructed absorptions (2-d middle slices) at each iteration step
self.list_reconstructions_result_path = self.path_manager.get_hdf5_file_save_path() + \
"/List_reconstructed_qpai_absorptions_" + str(self.wavelength) + "_" + self.VOLUME_NAME + ".npy"
self.list_2d_reconstructed_absorptions = np.load(self.list_reconstructions_result_path)
def tear_down(self):
# clean up files after test
os.remove(self.hdf5_path)
os.remove(self.list_reconstructions_result_path)
def visualise_result(self, show_figure_on_screen=True, save_path=None):
"""
Performs visualization of reconstruction results to allow for evaluation.
The resulting figure displays the ground truth absorption coefficients, the corresponding reconstruction
results and the difference between both for the middle plane in y-z and x-z direction, as well as the
reconstruction results at each iteration step in x-z direction. The number of iteration should be larger
than four to enable visualization.
"""
# compute absolute differences
difference_absorption = self.absorption_gt - self.reconstructed_absorption
if np.min(self.absorption_gt) > np.min(self.reconstructed_absorption):
cmin = np.min(self.reconstructed_absorption)
else:
cmin = np.min(self.absorption_gt)
if np.max(self.absorption_gt) > np.max(self.reconstructed_absorption):
cmax = np.max(self.absorption_gt)
else:
cmax = np.max(self.reconstructed_absorption)
x_pos = int(np.shape(self.absorption_gt)[0] / 2)
y_pos = int(np.shape(self.absorption_gt)[1] / 2)
results_x_z = [self.absorption_gt[:, y_pos, :], self.reconstructed_absorption[:, y_pos, :],
difference_absorption[:, y_pos, :]]
results_y_z = [self.absorption_gt[x_pos, :, :], self.reconstructed_absorption[x_pos, :, :],
difference_absorption[x_pos, :, :]]
label = ["Absorption coefficients: ${\mu_a}^{gt}$", "Reconstruction: ${\mu_a}^{reconstr.}$",
"Difference: ${\mu_a}^{gt} - {\mu_a}^{reconstr.}$"]
plt.figure(figsize=(20, 15))
plt.subplots_adjust(hspace=0.5, wspace=0.1)
plt.suptitle("Iterative qPAI Reconstruction")
for i, quantity in enumerate(results_y_z):
plt.subplot(4, int(np.ceil(len(self.list_2d_reconstructed_absorptions) / 2)), i + 1)
if i == 0:
plt.ylabel("y-z", fontsize=10)
plt.imshow(np.rot90(quantity, -1))
plt.title(label[i], fontsize=10)
plt.xticks(fontsize=6)
plt.yticks(fontsize=6)
plt.colorbar()
if i != 2:
plt.clim(cmin, cmax)
else:
plt.clim(np.min(difference_absorption), np.max(difference_absorption))
for i, quantity in enumerate(results_x_z):
plt.subplot(4, int(np.ceil(len(self.list_2d_reconstructed_absorptions) / 2)),
i + int(np.ceil(len(self.list_2d_reconstructed_absorptions) / 2)) + 1)
if i == 0:
plt.ylabel("x-z", fontsize=10)
plt.imshow(np.rot90(quantity, -1))
plt.title(label[i], fontsize=10)
plt.xticks(fontsize=6)
plt.yticks(fontsize=6)
plt.colorbar()
if i != 2:
plt.clim(cmin, cmax)
else:
plt.clim(np.min(difference_absorption), np.max(difference_absorption))
for i, quantity in enumerate(self.list_2d_reconstructed_absorptions):
plt.subplot(4, int(np.ceil(len(self.list_2d_reconstructed_absorptions) / 2)),
i + 2 * int(np.ceil(len(self.list_2d_reconstructed_absorptions) / 2)) + 1)
plt.title("Iteration step: " + str(i + 1), fontsize=8)
plt.imshow(np.rot90(quantity, -1)) # absorption maps in list are already 2-d
plt.colorbar()
plt.clim(cmin, cmax)
plt.axis('off')
if show_figure_on_screen:
plt.show()
else:
if save_path is None:
save_path = ""
plt.savefig(save_path + "qpai_reconstruction_test.png")
plt.close()
def create_example_tissue(self):
"""
This is a very simple example script of how to create a tissue definition.
It contains a muscular background, an epidermis layer on top of the muscles
and two blood vessels. It is used for volume creation.
"""
background_dictionary = Settings()
background_dictionary[Tags.MOLECULE_COMPOSITION] = TISSUE_LIBRARY.constant(0.1, 100.0, 0.90)
background_dictionary[Tags.STRUCTURE_TYPE] = Tags.BACKGROUND
epidermis_structure = Settings()
epidermis_structure[Tags.PRIORITY] = 1
epidermis_structure[Tags.STRUCTURE_START_MM] = [0, 0, 2]
epidermis_structure[Tags.STRUCTURE_END_MM] = [0, 0, 2.5]
epidermis_structure[Tags.MOLECULE_COMPOSITION] = TISSUE_LIBRARY.constant(2.2, 100.0, 0.9)
epidermis_structure[Tags.CONSIDER_PARTIAL_VOLUME] = True
epidermis_structure[Tags.ADHERE_TO_DEFORMATION] = True
epidermis_structure[Tags.STRUCTURE_TYPE] = Tags.HORIZONTAL_LAYER_STRUCTURE
vessel_structure_1 = Settings()
vessel_structure_1[Tags.PRIORITY] = 2
vessel_structure_1[Tags.STRUCTURE_START_MM] = [self.VOLUME_TRANSDUCER_DIM_IN_MM / 2.5, 0,
self.VOLUME_HEIGHT_IN_MM / 2]
vessel_structure_1[Tags.STRUCTURE_END_MM] = [self.VOLUME_TRANSDUCER_DIM_IN_MM / 2.5,
self.VOLUME_PLANAR_DIM_IN_MM, self.VOLUME_HEIGHT_IN_MM / 2]
vessel_structure_1[Tags.STRUCTURE_RADIUS_MM] = 1.75
vessel_structure_1[Tags.STRUCTURE_ECCENTRICITY] = 0.85
vessel_structure_1[Tags.MOLECULE_COMPOSITION] = TISSUE_LIBRARY.constant(5.2, 100.0, 0.9)
vessel_structure_1[Tags.CONSIDER_PARTIAL_VOLUME] = True
vessel_structure_1[Tags.ADHERE_TO_DEFORMATION] = True
vessel_structure_1[Tags.STRUCTURE_TYPE] = Tags.ELLIPTICAL_TUBULAR_STRUCTURE
vessel_structure_2 = Settings()
vessel_structure_2[Tags.PRIORITY] = 3
vessel_structure_2[Tags.STRUCTURE_START_MM] = [self.VOLUME_TRANSDUCER_DIM_IN_MM / 2, 0,
self.VOLUME_HEIGHT_IN_MM / 3]
vessel_structure_2[Tags.STRUCTURE_END_MM] = [self.VOLUME_TRANSDUCER_DIM_IN_MM / 2,
self.VOLUME_PLANAR_DIM_IN_MM, self.VOLUME_HEIGHT_IN_MM / 3]
vessel_structure_2[Tags.STRUCTURE_RADIUS_MM] = 0.75
vessel_structure_2[Tags.MOLECULE_COMPOSITION] = TISSUE_LIBRARY.constant(3.0, 100.0, 0.9)
vessel_structure_2[Tags.CONSIDER_PARTIAL_VOLUME] = True
vessel_structure_2[Tags.STRUCTURE_TYPE] = Tags.CIRCULAR_TUBULAR_STRUCTURE
tissue_dict = Settings()
tissue_dict[Tags.BACKGROUND] = background_dictionary
tissue_dict["epidermis"] = epidermis_structure
tissue_dict["vessel_1"] = vessel_structure_1
tissue_dict["vessel_2"] = vessel_structure_2
return tissue_dict
if __name__ == '__main__':
test = TestqPAIReconstruction()
test.run_test(show_figure_on_screen=False)
| [
"matplotlib.pyplot.title",
"numpy.load",
"os.remove",
"numpy.random.seed",
"matplotlib.pyplot.suptitle",
"simpa.utils.path_manager.PathManager",
"numpy.shape",
"matplotlib.pyplot.figure",
"numpy.rot90",
"simpa.ModelBasedVolumeCreationAdapter",
"matplotlib.pyplot.close",
"simpa.core.simulation.... | [((1488, 1501), 'simpa.utils.path_manager.PathManager', 'PathManager', ([], {}), '()\n', (1499, 1501), False, 'from simpa.utils.path_manager import PathManager\n'), ((1779, 1811), 'numpy.random.seed', 'np.random.seed', (['self.RANDOM_SEED'], {}), '(self.RANDOM_SEED)\n', (1793, 1811), True, 'import numpy as np\n'), ((2405, 2436), 'simpa.utils.Settings', 'Settings', (['self.general_settings'], {}), '(self.general_settings)\n', (2413, 2436), False, 'from simpa.utils import Tags, Settings, TISSUE_LIBRARY\n'), ((3991, 4037), 'simpa.core.simulation.simulate', 'simulate', (['pipeline', 'self.settings', 'self.device'], {}), '(pipeline, self.settings, self.device)\n', (3999, 4037), False, 'from simpa.core.simulation import simulate\n'), ((4942, 5053), 'simpa.io_handling.load_data_field', 'load_data_field', (['self.settings[Tags.SIMPA_OUTPUT_PATH]', 'Tags.DATA_FIELD_ABSORPTION_PER_CM', 'self.wavelength'], {}), '(self.settings[Tags.SIMPA_OUTPUT_PATH], Tags.\n DATA_FIELD_ABSORPTION_PER_CM, self.wavelength)\n', (4957, 5053), False, 'from simpa.io_handling import load_data_field\n'), ((5853, 5929), 'simpa.io_handling.load_data_field', 'load_data_field', (['self.hdf5_path', 'Tags.ITERATIVE_qPAI_RESULT', 'self.wavelength'], {}), '(self.hdf5_path, Tags.ITERATIVE_qPAI_RESULT, self.wavelength)\n', (5868, 5929), False, 'from simpa.io_handling import load_data_field\n'), ((6280, 6326), 'numpy.load', 'np.load', (['self.list_reconstructions_result_path'], {}), '(self.list_reconstructions_result_path)\n', (6287, 6326), True, 'import numpy as np\n'), ((6397, 6422), 'os.remove', 'os.remove', (['self.hdf5_path'], {}), '(self.hdf5_path)\n', (6406, 6422), False, 'import os\n'), ((6431, 6479), 'os.remove', 'os.remove', (['self.list_reconstructions_result_path'], {}), '(self.list_reconstructions_result_path)\n', (6440, 6479), False, 'import os\n'), ((8169, 8197), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(20, 15)'}), '(figsize=(20, 15))\n', (8179, 8197), True, 'import matplotlib.pyplot as plt\n'), ((8206, 8249), 'matplotlib.pyplot.subplots_adjust', 'plt.subplots_adjust', ([], {'hspace': '(0.5)', 'wspace': '(0.1)'}), '(hspace=0.5, wspace=0.1)\n', (8225, 8249), True, 'import matplotlib.pyplot as plt\n'), ((8258, 8303), 'matplotlib.pyplot.suptitle', 'plt.suptitle', (['"""Iterative qPAI Reconstruction"""'], {}), "('Iterative qPAI Reconstruction')\n", (8270, 8303), True, 'import matplotlib.pyplot as plt\n'), ((10264, 10275), 'matplotlib.pyplot.close', 'plt.close', ([], {}), '()\n', (10273, 10275), True, 'import matplotlib.pyplot as plt\n'), ((10600, 10610), 'simpa.utils.Settings', 'Settings', ([], {}), '()\n', (10608, 10610), False, 'from simpa.utils import Tags, Settings, TISSUE_LIBRARY\n'), ((10670, 10710), 'simpa.utils.TISSUE_LIBRARY.constant', 'TISSUE_LIBRARY.constant', (['(0.1)', '(100.0)', '(0.9)'], {}), '(0.1, 100.0, 0.9)\n', (10693, 10710), False, 'from simpa.utils import Tags, Settings, TISSUE_LIBRARY\n'), ((10812, 10822), 'simpa.utils.Settings', 'Settings', ([], {}), '()\n', (10820, 10822), False, 'from simpa.utils import Tags, Settings, TISSUE_LIBRARY\n'), ((11057, 11097), 'simpa.utils.TISSUE_LIBRARY.constant', 'TISSUE_LIBRARY.constant', (['(2.2)', '(100.0)', '(0.9)'], {}), '(2.2, 100.0, 0.9)\n', (11080, 11097), False, 'from simpa.utils import Tags, Settings, TISSUE_LIBRARY\n'), ((11339, 11349), 'simpa.utils.Settings', 'Settings', ([], {}), '()\n', (11347, 11349), False, 'from simpa.utils import Tags, Settings, TISSUE_LIBRARY\n'), ((11964, 12004), 'simpa.utils.TISSUE_LIBRARY.constant', 'TISSUE_LIBRARY.constant', (['(5.2)', '(100.0)', '(0.9)'], {}), '(5.2, 100.0, 0.9)\n', (11987, 12004), False, 'from simpa.utils import Tags, Settings, TISSUE_LIBRARY\n'), ((12245, 12255), 'simpa.utils.Settings', 'Settings', ([], {}), '()\n', (12253, 12255), False, 'from simpa.utils import Tags, Settings, TISSUE_LIBRARY\n'), ((12803, 12843), 'simpa.utils.TISSUE_LIBRARY.constant', 'TISSUE_LIBRARY.constant', (['(3.0)', '(100.0)', '(0.9)'], {}), '(3.0, 100.0, 0.9)\n', (12826, 12843), False, 'from simpa.utils import Tags, Settings, TISSUE_LIBRARY\n'), ((13013, 13023), 'simpa.utils.Settings', 'Settings', ([], {}), '()\n', (13021, 13023), False, 'from simpa.utils import Tags, Settings, TISSUE_LIBRARY\n'), ((3830, 3876), 'simpa.ModelBasedVolumeCreationAdapter', 'ModelBasedVolumeCreationAdapter', (['self.settings'], {}), '(self.settings)\n', (3861, 3876), False, 'from simpa import MCXAdapter, ModelBasedVolumeCreationAdapter, GaussianNoise\n'), ((3890, 3915), 'simpa.MCXAdapter', 'MCXAdapter', (['self.settings'], {}), '(self.settings)\n', (3900, 3915), False, 'from simpa import MCXAdapter, ModelBasedVolumeCreationAdapter, GaussianNoise\n'), ((3929, 3972), 'simpa.GaussianNoise', 'GaussianNoise', (['self.settings', '"""noise_model"""'], {}), "(self.settings, 'noise_model')\n", (3942, 3972), False, 'from simpa import MCXAdapter, ModelBasedVolumeCreationAdapter, GaussianNoise\n'), ((5287, 5378), 'scipy.ndimage.zoom', 'zoom', (['absorption_gt', 'component_settings[Tags.DOWNSCALE_FACTOR]'], {'order': '(1)', 'mode': '"""nearest"""'}), "(absorption_gt, component_settings[Tags.DOWNSCALE_FACTOR], order=1,\n mode='nearest')\n", (5291, 5378), False, 'from scipy.ndimage import zoom\n'), ((5460, 5510), 'scipy.ndimage.zoom', 'zoom', (['absorption_gt', '(0.73)'], {'order': '(1)', 'mode': '"""nearest"""'}), "(absorption_gt, 0.73, order=1, mode='nearest')\n", (5464, 5510), False, 'from scipy.ndimage import zoom\n'), ((7177, 7203), 'numpy.min', 'np.min', (['self.absorption_gt'], {}), '(self.absorption_gt)\n', (7183, 7203), True, 'import numpy as np\n'), ((7206, 7243), 'numpy.min', 'np.min', (['self.reconstructed_absorption'], {}), '(self.reconstructed_absorption)\n', (7212, 7243), True, 'import numpy as np\n'), ((7264, 7301), 'numpy.min', 'np.min', (['self.reconstructed_absorption'], {}), '(self.reconstructed_absorption)\n', (7270, 7301), True, 'import numpy as np\n'), ((7335, 7361), 'numpy.min', 'np.min', (['self.absorption_gt'], {}), '(self.absorption_gt)\n', (7341, 7361), True, 'import numpy as np\n'), ((7374, 7400), 'numpy.max', 'np.max', (['self.absorption_gt'], {}), '(self.absorption_gt)\n', (7380, 7400), True, 'import numpy as np\n'), ((7403, 7440), 'numpy.max', 'np.max', (['self.reconstructed_absorption'], {}), '(self.reconstructed_absorption)\n', (7409, 7440), True, 'import numpy as np\n'), ((7461, 7487), 'numpy.max', 'np.max', (['self.absorption_gt'], {}), '(self.absorption_gt)\n', (7467, 7487), True, 'import numpy as np\n'), ((7521, 7558), 'numpy.max', 'np.max', (['self.reconstructed_absorption'], {}), '(self.reconstructed_absorption)\n', (7527, 7558), True, 'import numpy as np\n'), ((8582, 8614), 'matplotlib.pyplot.title', 'plt.title', (['label[i]'], {'fontsize': '(10)'}), '(label[i], fontsize=10)\n', (8591, 8614), True, 'import matplotlib.pyplot as plt\n'), ((8627, 8649), 'matplotlib.pyplot.xticks', 'plt.xticks', ([], {'fontsize': '(6)'}), '(fontsize=6)\n', (8637, 8649), True, 'import matplotlib.pyplot as plt\n'), ((8662, 8684), 'matplotlib.pyplot.yticks', 'plt.yticks', ([], {'fontsize': '(6)'}), '(fontsize=6)\n', (8672, 8684), True, 'import matplotlib.pyplot as plt\n'), ((8697, 8711), 'matplotlib.pyplot.colorbar', 'plt.colorbar', ([], {}), '()\n', (8709, 8711), True, 'import matplotlib.pyplot as plt\n'), ((9243, 9275), 'matplotlib.pyplot.title', 'plt.title', (['label[i]'], {'fontsize': '(10)'}), '(label[i], fontsize=10)\n', (9252, 9275), True, 'import matplotlib.pyplot as plt\n'), ((9288, 9310), 'matplotlib.pyplot.xticks', 'plt.xticks', ([], {'fontsize': '(6)'}), '(fontsize=6)\n', (9298, 9310), True, 'import matplotlib.pyplot as plt\n'), ((9323, 9345), 'matplotlib.pyplot.yticks', 'plt.yticks', ([], {'fontsize': '(6)'}), '(fontsize=6)\n', (9333, 9345), True, 'import matplotlib.pyplot as plt\n'), ((9358, 9372), 'matplotlib.pyplot.colorbar', 'plt.colorbar', ([], {}), '()\n', (9370, 9372), True, 'import matplotlib.pyplot as plt\n'), ((9975, 9989), 'matplotlib.pyplot.colorbar', 'plt.colorbar', ([], {}), '()\n', (9987, 9989), True, 'import matplotlib.pyplot as plt\n'), ((10002, 10022), 'matplotlib.pyplot.clim', 'plt.clim', (['cmin', 'cmax'], {}), '(cmin, cmax)\n', (10010, 10022), True, 'import matplotlib.pyplot as plt\n'), ((10035, 10050), 'matplotlib.pyplot.axis', 'plt.axis', (['"""off"""'], {}), "('off')\n", (10043, 10050), True, 'import matplotlib.pyplot as plt\n'), ((10098, 10108), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (10106, 10108), True, 'import matplotlib.pyplot as plt\n'), ((10200, 10255), 'matplotlib.pyplot.savefig', 'plt.savefig', (["(save_path + 'qpai_reconstruction_test.png')"], {}), "(save_path + 'qpai_reconstruction_test.png')\n", (10211, 10255), True, 'import matplotlib.pyplot as plt\n'), ((3556, 3658), 'numpy.asarray', 'np.asarray', (['[self.settings[Tags.DIM_VOLUME_X_MM] / 2, self.settings[Tags.\n DIM_VOLUME_Y_MM] / 2, 0]'], {}), '([self.settings[Tags.DIM_VOLUME_X_MM] / 2, self.settings[Tags.\n DIM_VOLUME_Y_MM] / 2, 0])\n', (3566, 3658), True, 'import numpy as np\n'), ((5587, 5648), 'simpa.core.processing_components.monospectral.iterative_qPAI_algorithm.IterativeqPAI', 'IterativeqPAI', (['self.settings', '"""iterative_qpai_reconstruction"""'], {}), "(self.settings, 'iterative_qpai_reconstruction')\n", (5600, 5648), False, 'from simpa.core.processing_components.monospectral.iterative_qPAI_algorithm import IterativeqPAI\n'), ((8492, 8522), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""y-z"""'], {'fontsize': '(10)'}), "('y-z', fontsize=10)\n", (8502, 8522), True, 'import matplotlib.pyplot as plt\n'), ((8546, 8568), 'numpy.rot90', 'np.rot90', (['quantity', '(-1)'], {}), '(quantity, -1)\n', (8554, 8568), True, 'import numpy as np\n'), ((8751, 8771), 'matplotlib.pyplot.clim', 'plt.clim', (['cmin', 'cmax'], {}), '(cmin, cmax)\n', (8759, 8771), True, 'import matplotlib.pyplot as plt\n'), ((9153, 9183), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""x-z"""'], {'fontsize': '(10)'}), "('x-z', fontsize=10)\n", (9163, 9183), True, 'import matplotlib.pyplot as plt\n'), ((9207, 9229), 'numpy.rot90', 'np.rot90', (['quantity', '(-1)'], {}), '(quantity, -1)\n', (9215, 9229), True, 'import numpy as np\n'), ((9412, 9432), 'matplotlib.pyplot.clim', 'plt.clim', (['cmin', 'cmax'], {}), '(cmin, cmax)\n', (9420, 9432), True, 'import matplotlib.pyplot as plt\n'), ((9896, 9918), 'numpy.rot90', 'np.rot90', (['quantity', '(-1)'], {}), '(quantity, -1)\n', (9904, 9918), True, 'import numpy as np\n'), ((7580, 7608), 'numpy.shape', 'np.shape', (['self.absorption_gt'], {}), '(self.absorption_gt)\n', (7588, 7608), True, 'import numpy as np\n'), ((7637, 7665), 'numpy.shape', 'np.shape', (['self.absorption_gt'], {}), '(self.absorption_gt)\n', (7645, 7665), True, 'import numpy as np\n'), ((8815, 8844), 'numpy.min', 'np.min', (['difference_absorption'], {}), '(difference_absorption)\n', (8821, 8844), True, 'import numpy as np\n'), ((8846, 8875), 'numpy.max', 'np.max', (['difference_absorption'], {}), '(difference_absorption)\n', (8852, 8875), True, 'import numpy as np\n'), ((9476, 9505), 'numpy.min', 'np.min', (['difference_absorption'], {}), '(difference_absorption)\n', (9482, 9505), True, 'import numpy as np\n'), ((9507, 9536), 'numpy.max', 'np.max', (['difference_absorption'], {}), '(difference_absorption)\n', (9513, 9536), True, 'import numpy as np\n')] |
#!/usr/bin/env python
import os
import numpy as np
import codecs
from scipy.optimize import curve_fit
from scipy.interpolate import interp1d
import matplotlib.pyplot as plt
from collections import defaultdict
import thepipe as tp
import h5py
from .tools import (
gaussian,
calculate_charges,
bin_data,
calculate_rise_times,
read_spectral_scan,
read_datetime,
convert_to_secs,
choose_ref,
peak_finder,
remove_double_peaks,
peaks_with_signal,
)
from .pmt_resp_func import ChargeHistFitter
from .constants import hama_phd_qe
from .core import WavesetReader
class FilePump(tp.Module):
"""
iterates over a set of filenames
"""
def configure(self):
self.filenames = self.get("filenames")
self.max_count = len(self.filenames)
self.index = 0
def process(self, blob):
if self.index >= self.max_count:
raise StopIteration
blob["filename"] = self.filenames[self.index]
self.index += 1
return blob
def finish(self):
self.cprint(f"Read {self.index} files!")
class QECalibrator(tp.Module):
"""Reads measured currents from PMT and PHD and calculates the QE of the PMT
"""
def configure(self):
self.phd_filenames = self.get("phd_filenames")
self.global_qe_shift = self.get("global_qe_shift")
phd_qe = hama_phd_qe.T
self.phd_qe_interp = interp1d(phd_qe[0], phd_qe[1], kind="cubic")
def process(self, blob):
pmt_filename = blob["filename"]
phd_filename = choose_ref(self.phd_filenames, pmt_filename)
wl_pmt, i_pmt = read_spectral_scan(pmt_filename)
wl_phd, i_phd = read_spectral_scan(phd_filename)
if np.allclose(wl_pmt, wl_phd):
wl = wl_pmt + self.global_qe_shift
else:
self.log.error("PMT and PHD wavelengths do not match!")
raise StopIteration
qe = i_pmt / i_phd * self.phd_qe_interp(wl) / 100
blob["wl"] = wl
blob["qe"] = qe
blob["pmt_id"] = pmt_filename.split("/")[-1].split(".")[0]
blob["global_qe_shift"] = self.global_qe_shift
return blob
class QEWriter(tp.Module):
"""Writes QE in text file"""
def configure(self):
self.filepath = self.get("filepath")
def process(self, blob):
shift = blob["global_qe_shift"]
pmt_id = blob["pmt_id"]
qe_filename = f"{self.filepath}/qe_{pmt_id}_wl_shift_{shift}_nm.txt"
np.savetxt(qe_filename, np.array([blob["wl"], blob["qe"]]).T)
return blob
class NominalHVFinder(tp.Module):
"""
finds the nominal HV for a certain gain
"""
def configure(self):
self.gain = self.get("gain")
def process(self, blob):
filename = blob["filename"]
f = h5py.File(filename, "r")
nominal_hv = self.find_nominal_hv(f, self.gain)
blob["nominal_gain"] = self.gain
blob["nominal_hv"] = nominal_hv
return blob
def find_nominal_hv(self, f, nominal_gain):
gains = []
hvs = []
keys = f.keys()
for key in keys:
gains.append(f[key]["fit_results"]["gain"][()])
hvs.append(int(key))
gains = np.array(gains)
hvs = np.array(hvs)
diff = abs(np.array(gains) - nominal_gain)
nominal_hv = int(hvs[diff == np.min(diff)])
return nominal_hv
class FileReader(tp.Module):
"""
pipe module that reads h5py files and writes waveforms and waveform info
into the blob
"""
def process(self, blob):
filename = blob["filename"]
blob["pmt_id"] = filename.split("/")[-1].split(".")[0]
self.cprint(f"Reading file: {filename}")
f = h5py.File(filename, "r")
nominal_hv = blob["nominal_hv"]
blob["waveforms"] = f[f"{nominal_hv}"]["waveforms"][:]
blob["h_int"] = f[f"{nominal_hv}"]["waveform_info/h_int"][()]
blob["v_gain"] = f[f"{nominal_hv}"]["waveform_info/v_gain"][()]
blob["gain_norm"] = blob["v_gain"] * blob["h_int"] / 50 / 1.6022e-19
f.close()
return blob
class ChargeCalculator(tp.Module):
"""
pipe module that calculates charges of waveforms
"""
def configure(self):
self.ped_range = self.get("ped_range")
self.sig_range = self.get("sig_range")
def process(self, blob):
charges = calculate_charges(
blob["waveforms"],
self.ped_range[0],
self.ped_range[1],
self.sig_range[0],
self.sig_range[1],
)
charges = charges * blob["gain_norm"]
blob["charges"] = charges
x, y = bin_data(charges, bins=200, range=(-0.3e7, 4e7))
blob["charge_distribution"] = (x, y)
return blob
class PMTResponseFitter(tp.Module):
"""
pipe module that fits charge distribution with
PMT response function
"""
def configure(self):
self.mod = self.get("mod")
def process(self, blob):
x, y = blob["charge_distribution"]
fitter = ChargeHistFitter()
fitter.pre_fit(x, y, print_level=0)
fitter.fit_pmt_resp_func(
x, y, mod=self.mod, print_level=0, fixed_parameters=[]
)
if not fitter.success:
return
blob["popt_prf"] = fitter.popt_prf
blob["popt_ped"] = fitter.popt_ped
blob["popt_spe"] = fitter.popt_spe
blob["fit_function"] = fitter.used_fit_function
blob["spe_resolution"] = (
fitter.popt_prf["spe_sigma"] / fitter.popt_prf["spe_charge"]
)
blob["nphe"] = fitter.popt_prf["nphe"]
return blob
class PeakToValleyCalculator(tp.Module):
"""
pipe module that calculates the peak-to-valley ratio of a PMT response
"""
def process(self, blob):
fit_function = blob["fit_function"]
fine_xs = np.linspace(-0.5e7, 3e7, 10000)
valley_mask = (fine_xs > blob["popt_ped"]["mean"]) & (
fine_xs < blob["popt_spe"]["mean"]
)
valley = np.min(fit_function(fine_xs, **blob["popt_prf"])[valley_mask])
peak_mask = fine_xs > (
blob["popt_ped"]["mean"] + blob["popt_ped"]["sigma"] * 3
)
peak = np.max(fit_function(fine_xs, **blob["popt_prf"])[peak_mask])
blob["peak_to_valley"] = peak / valley
return blob
class TransitTimeCalculator(tp.Module):
"""
pipe module that calculates transit times and TTS of pmt signals
"""
def configure(self):
self.charge_threshold = self.get("charge_threshold")
self.voltage_threshold = self.get("voltage_threshold")
def process(self, blob):
charges = blob["charges"]
signal_mask = charges > self.charge_threshold * (
blob["popt_prf"]["spe_charge"] + blob["popt_ped"]["mean"]
)
zeroed_signals = blob["waveforms"][signal_mask] - np.mean(
blob["waveforms"][signal_mask][:, :200]
)
transit_times = (
np.argmax(
zeroed_signals * blob["v_gain"] < self.voltage_threshold, axis=1
)
* blob["h_int"]
* 1e9
)
transit_times = transit_times[transit_times != 0]
blob["transit_times"] = transit_times
t, n = bin_data(transit_times, range=(0, 100), bins=200)
blob["tt_distribution"] = (t, n)
mean_0 = t[np.argmax(n)]
try:
tt_popt, _ = curve_fit(gaussian, t, n, p0=[mean_0, 2, 1e5])
except RuntimeError:
tt_popt = [0, 0, 0]
blob["tt_popt"] = tt_popt
blob["TTS"] = tt_popt[1]
blob["transit_time"] = tt_popt[0]
return blob
class RiseTimeCalculator(tp.Module):
"""
rise time calculator
Parameters
----------
relative_thresholds: tuple(float)
relative lower and upper t
blob["zeroed_signals"] = zeroed_signalshreshold inbetween which to calculate
rise time
relative_charge_range: tuple(float)
relative range of spe charge which are used for the rise time
calculation
"""
def configure(self):
self.relative_thresholds = self.get("relative_thresholds")
self.relative_charge_range = self.get("relative_charge_range")
def process(self, blob):
spe_charge_peak = (
blob["popt_prf"]["spe_charge"] - blob["popt_prf"]["ped_mean"]
)
signals = blob["waveforms"][
(blob["charges"] > spe_charge_peak * self.relative_charge_range[0])
& (
blob["charges"]
< spe_charge_peak * self.relative_charge_range[1]
)
]
rise_times = calculate_rise_times(signals, self.relative_thresholds)
blob["rise_time"] = np.mean(rise_times)
return blob
class MeanSpeAmplitudeCalculator(tp.Module):
"""
mean spe amplitude calculator
Parameters
----------
relative_charge_range: tuple(float) (0.8, 1.2)
relative range of spe charge which are used for the mean amplitude
calculation
"""
def configure(self):
self.relative_charge_range = self.get("relative_charge_range")
def process(self, blob):
spe_charge_peak = (
blob["popt_prf"]["spe_charge"] - blob["popt_prf"]["ped_mean"]
)
spe_mask = (
blob["charges"] > (spe_charge_peak * self.relative_charge_range[0])
) & (
blob["charges"] < (spe_charge_peak * self.relative_charge_range[1])
)
spes = blob["waveforms"][spe_mask] * blob["v_gain"]
zeroed_spes = (spes.T - np.mean(spes[:, :150], axis=1)).T
spe_amplitudes = np.min(zeroed_spes, axis=1)
blob["mean_spe_amplitude"] = np.mean(spe_amplitudes)
return blob
class PrePulseCalculator(tp.Module):
"""
calculates pre-pulse probability
"""
def configure(self):
self.time_range = self.get("time_range")
def process(self, blob):
max_time = blob["tt_popt"][0] + self.time_range[1]
min_time = blob["tt_popt"][0] + self.time_range[0]
blob["pre_max_time"] = max_time
blob["pre_min_time"] = min_time
transit_times = blob["transit_times"]
n_pre_pulses = len(
transit_times[
(transit_times > min_time) & (transit_times < max_time)
]
)
blob["pre_pulse_prob"] = n_pre_pulses / len(transit_times)
return blob
class PrePulseChargeCalculator(tp.Module):
"""
calculates pre-pulse probability via their charges
"""
def configure(self):
self.n_sigma = self.get("n_sigma", default=5)
def process(self, blob):
waveforms = blob["waveforms"]
blob["precharges_n_sigma"] = self.n_sigma
peak_position = np.argmin(np.mean(waveforms, axis=0))
pre_charges = calculate_charges(
waveforms, 0, 70, peak_position - 100, peak_position - 30
)
pre_x, pre_y = bin_data(pre_charges, range=(-500, 3000), bins=200)
blob["precharge_pre_charge_distribution"] = (pre_x, pre_y)
charges = calculate_charges(
waveforms, 0, 130, peak_position - 30, peak_position + 100
)
x, y = bin_data(charges, range=(-500, 3000), bins=200)
blob["precharge_charge_distribution"] = (x, y)
popt_pre, pcov_pre = curve_fit(
gaussian, pre_x, pre_y, p0=[0, 100, 100000]
)
popt, pcov = curve_fit(gaussian, x, y, p0=[0, 100, 100000])
blob["precharge_popt_pre"] = popt_pre
blob["precharge_popt"] = popt
charge_sum = np.sum(charges[charges > popt[0] + popt[1] * self.n_sigma])
charge_sum_pre = np.sum(
pre_charges[pre_charges > popt_pre[0] + popt_pre[1] * self.n_sigma]
)
pre_prob_charge = charge_sum_pre / charge_sum
blob["pre_pulse_prob_charge"] = pre_prob_charge
return blob
class DelayedPulseCalculator(tp.Module):
"""
calculates delayed pulse probability
"""
def process(self, blob):
min_time = blob["tt_popt"][0] + 15
blob["delayed_min_time"] = min_time
transit_times = blob["transit_times"]
n_delayed_pulses = len(transit_times[transit_times > min_time])
blob["delayed_pulse_prob"] = n_delayed_pulses / len(transit_times)
return blob
class ResultWriter(tp.Module):
"""
writes fitted and calculated PMT parameters to text file
"""
def configure(self):
self.filename = self.get("filename")
self.results = defaultdict(list)
self.parameters_to_write = [
"pmt_id",
"nominal_hv",
"nphe",
"peak_to_valley",
"transit_time",
"TTS",
"pre_pulse_prob",
"delayed_pulse_prob",
"pre_pulse_prob_charge",
"spe_resolution",
"rise_time",
"mean_spe_amplitude",
]
def process(self, blob):
for parameter in self.parameters_to_write:
self.results[parameter].append(blob[parameter])
return blob
def finish(self):
outfile = open(self.filename, "w")
for parameter in self.parameters_to_write:
outfile.write(f"{parameter} ")
outfile.write("\n")
for i in range(len(self.results[self.parameters_to_write[0]])):
for parameter in self.parameters_to_write:
outfile.write(f"{self.results[parameter][i]} ")
outfile.write("\n")
outfile.close()
class ResultPlotter(tp.Module):
"""
pipe module that plots and saves figures of:
- charge distribution,
- PMT response fit,
- transit time distribution,
- pre pulse charges
if available
"""
def configure(self):
self.file_path = self.get("file_path")
self.results = defaultdict(list)
self.parameters_for_plots = [
"pmt_id",
"nominal_gain",
"nominal_hv",
"charge_distribution",
"popt_prf",
"fit_function",
"peak_to_valley",
"tt_distribution",
"tt_popt",
"pre_pulse_prob",
"pre_max_time",
"delayed_pulse_prob",
"delayed_min_time",
"pre_pulse_prob_charge",
"precharge_charge_distribution",
"precharge_pre_charge_distribution",
"precharge_popt",
"precharge_popt_pre",
"precharges_n_sigma",
"pre_pulse_prob_charge",
]
def process(self, blob):
for parameter in self.parameters_for_plots:
self.results[parameter].append(blob[parameter])
return blob
def finish(self):
os.mkdir(self.file_path)
for i in range(len(self.results[self.parameters_for_plots[0]])):
fig, ax = plt.subplots(2, 2, figsize=(16, 12))
ax = ax.flatten()
fig.suptitle(
f"PMT: {self.results['pmt_id'][i]}; "
f"nominal gain: {self.results['nominal_gain'][i]}; "
f"nominal HV: {self.results['nominal_hv'][i]}"
)
ax[0].set_title("charge distribution")
ax[1].set_title("TT distribution")
if "charge_distribution" in self.results:
x, y = self.results["charge_distribution"][i]
ax[0].semilogy(x, y)
ax[0].set_ylim(0.1, 1e5)
ax[0].set_xlabel("gain")
ax[0].set_ylabel("counts")
if "popt_prf" in self.results:
func = self.results["fit_function"][i]
popt_prf = self.results["popt_prf"][i]
ax[0].semilogy(x, func(x, **popt_prf))
gain = self.results["popt_prf"][i]["spe_charge"]
nphe = self.results["popt_prf"][i]["nphe"]
ax[0].text(1e7, 10000, f"gain: {round(gain)}")
ax[0].text(1e7, 3000, f"nphe: {round(nphe, 3)}")
if "peak_to_valley" in self.results:
ax[0].text(
1e7,
1000,
f"peak to valley: {round(self.results['peak_to_valley'][i], 3)}",
)
if "tt_distribution" in self.results:
x, y = self.results["tt_distribution"][i]
ax[1].semilogy(x, y)
ax[1].set_ylim(0.1, 1e4)
ax[1].set_xlabel("transit time [ns]")
ax[1].set_ylabel("counts")
if "tt_popt" in self.results:
tt_popt = self.results["tt_popt"][i]
ax[1].semilogy(x, gaussian(x, *tt_popt))
ax[1].text(0, 3000, f"TT: {round(tt_popt[0], 3)} ns")
ax[1].text(0, 1000, f"TTS: {round(tt_popt[1], 3)} ns")
if "pre_pulse_prob" in self.results:
pre_pulse_prob = self.results["pre_pulse_prob"][i]
ax[1].text(70, 3000, f"pre: {round(pre_pulse_prob, 3)}")
ax[1].axvline(
self.results["pre_max_time"][i], color="black", lw=1
)
if "delayed_pulse_prob" in self.results:
delayed_pulse_prob = self.results["delayed_pulse_prob"][i]
ax[1].text(70, 1000, f"delayed: {round(delayed_pulse_prob, 3)}")
ax[1].axvline(
self.results["delayed_min_time"][i], color="black", lw=1
)
if "pre_pulse_prob_charge" in self.results:
x, y = self.results["precharge_charge_distribution"][i]
x_pre, y_pre = self.results[
"precharge_pre_charge_distribution"
][i]
popt = self.results["precharge_popt"][i]
popt_pre = self.results["precharge_popt_pre"][i]
n_sigma = self.results["precharges_n_sigma"][i]
ax[2].semilogy(x, y)
ax[2].plot(x, gaussian(x, *popt))
ax[2].set_ylim(0.1, 1e5)
ax[2].axvline(
popt[0] + popt[1] * n_sigma,
color="black",
label=f"mean(ped) + {n_sigma} * sigma(ped)",
lw=1,
)
ax[2].set_xlabel("charge [A.U.]")
ax[2].set_ylabel("counts")
ax[2].legend()
ax[3].semilogy(x_pre, y_pre)
ax[3].plot(x_pre, gaussian(x_pre, *popt_pre))
ax[3].set_ylim(0.1, 1e5)
ax[3].axvline(
popt_pre[0] + popt_pre[1] * n_sigma,
color="black",
label=f"mean(ped) + {n_sigma} * sigma(ped)",
lw=1,
)
ax[3].set_xlabel("charge [A.U.]")
ax[3].set_ylabel("counts")
ax[3].text(
1000,
1000,
f"pre_charge: {round(self.results['pre_pulse_prob_charge'][i], 3)}",
)
ax[3].legend()
fig.savefig(
f"{self.file_path}/{self.results['pmt_id'][i]}_{self.results['nominal_gain'][i]}.png",
bbox_inches="tight",
)
plt.close(fig)
class AfterpulseFileReader(tp.Module):
"""
pipe module that reads h5py afterpulse files and writes waveforms
and waveform info of reference and main measurement into the blob
"""
def process(self, blob):
filename = blob["filename"]
blob["pmt_id"] = os.path.basename(filename).split("_")[-1].split(".")[0]
self.cprint(f"Reading file: {filename}")
reader = WavesetReader(filename)
for k in reader.wavesets:
if "ref" in k:
blob["waveforms_ref"] = reader[k].waveforms
blob["h_int_ref"] = reader[k].h_int
else:
blob["waveforms"] = reader[k].waveforms
blob["h_int"] = reader[k].h_int
return blob
class AfterpulseNpheCalculator(tp.Module):
"""
pipe module that calculates the mean number of photoelectrons of
the afterpulse data - used for correction of the afterpulse probability later
Parameters
----------
ped_sig_range_ref: tuple(int)
pedestal and signal integration range for reference measurement (spe regime)
ap_integration_window_half_width: int
half width of pedestal and signal integration range of afterpulse data
n_gaussians: int
number of gaussians used for afterpulse charge spectrum fit
fit_mod_ref: str
fit mod used for PMT response fit to reference data
"""
def configure(self):
self.ped_sig_range_ref = self.get(
"ped_sig_range", default=(0, 200, 200, 400)
)
self.ap_integration_window_half_width = self.get(
"ap_integration_window_half_width", default=25
)
self.n_gaussians = self.get("n_gaussians", default=25)
self.fit_mod_ref = self.get("fit_mod_ref", default=False)
def process(self, blob):
blob["fit_info"] = {}
charges_ref = calculate_charges(
blob["waveforms_ref"], *self.ped_sig_range_ref
)
x_ref, y_ref = bin_data(charges_ref, bins=200)
fitter_ref = ChargeHistFitter()
fitter_ref.pre_fit(x_ref, y_ref, print_level=0)
fitter_ref.fit_pmt_resp_func(
x_ref, y_ref, print_level=0, mod=self.fit_mod_ref
)
blob["fit_info"]["x_ref"] = x_ref
blob["fit_info"]["y_ref"] = y_ref
blob["fit_info"]["prf_values_ref"] = fitter_ref.opt_prf_values
blob["fit_info"]["ped_values_ref"] = fitter_ref.opt_ped_values
blob["fit_info"]["spe_values_ref"] = fitter_ref.opt_spe_values
time_bin_ratio = blob["h_int_ref"] / blob["h_int"]
waveforms = blob["waveforms"]
sig_pos = np.argmin(np.mean(waveforms, axis=0))
blob["sig_pos"] = sig_pos
ped_sig_range = [
sig_pos - 3 * self.ap_integration_window_half_width,
sig_pos - self.ap_integration_window_half_width,
sig_pos - self.ap_integration_window_half_width,
sig_pos + self.ap_integration_window_half_width,
]
charges = calculate_charges(waveforms, *ped_sig_range)
x, y = bin_data(charges, bins=200)
fitter = ChargeHistFitter()
fitter.fix_ped_spe(
fitter_ref.popt_prf["ped_mean"] * time_bin_ratio,
fitter_ref.popt_prf["ped_sigma"] * time_bin_ratio,
fitter_ref.popt_prf["spe_charge"] * time_bin_ratio,
fitter_ref.popt_prf["spe_sigma"] * time_bin_ratio,
)
fitter.pre_fit(x, y, print_level=0)
fitter.fit_pmt_resp_func(
x,
y,
n_gaussians=self.n_gaussians,
strong_limits=False,
print_level=0,
)
blob["fit_info"]["x"] = x
blob["fit_info"]["y"] = y
blob["fit_info"]["fit_values"] = fitter.opt_prf_values
blob["ap_nphe"] = fitter.popt_prf["nphe"]
return blob
class AfterpulseCalculator(tp.Module):
"""
pipe module that calculates afterpulse probability
Parameters
----------
threshold: float
threshold for peak finder
rel_ap_time_window: tuple(float)
time window relative to main signal in which afterpulses are counted
double_peak_distance: int
max distance between peaks to count as double peak
ap_integration_window_half_width: int
half width of pedestal and signal integration range of afterpulse data
"""
def configure(self):
self.threshold = self.get("threshold")
self.rel_ap_range = self.get("rel_ap_range", default=(0.1, 12))
self.double_peak_distance = self.get("double_peak_distance", default=20)
self.ap_integration_window_half_width = self.get(
"ap_integration_window_half_width", default=25
)
def process(self, blob):
S_TO_US = 1e6
waveforms = blob["waveforms"]
waveforms = (waveforms.T - np.mean(waveforms[:, :100], axis=1)).T
peaks = peak_finder(waveforms, self.threshold)
peaks = remove_double_peaks(peaks, distance=self.double_peak_distance)
sig_pos = blob["sig_pos"]
peaks = peaks_with_signal(
peaks,
(
sig_pos - self.ap_integration_window_half_width,
sig_pos + self.ap_integration_window_half_width,
),
)
flat_peaks = []
for peak in peaks:
for p in peak:
flat_peaks.append(p)
ap_dist_us = np.array(flat_peaks) * blob["h_int"] * S_TO_US
sig_pos_us = sig_pos * blob["h_int"] * S_TO_US
blob["ap_dist_us"] = ap_dist_us
dr_window_len = sig_pos_us - 0.05
ap_window_len = self.rel_ap_range[1] - self.rel_ap_range[0]
n_dr_hits = (
np.sum(ap_dist_us < (sig_pos_us - 0.05))
* ap_window_len
/ dr_window_len
)
blob["n_dr_hits"] = n_dr_hits
n_afterpulses = np.sum(
(ap_dist_us > (sig_pos_us + self.rel_ap_range[0]))
& (ap_dist_us < (sig_pos_us + self.rel_ap_range[1]))
)
blob["n_afterpulses"] = n_afterpulses
afterpulse_prob = (
(n_afterpulses - n_dr_hits) / len(peaks) / blob["ap_nphe"]
)
blob["afterpulse_prob"] = afterpulse_prob
return blob
class AfterpulseResultWriter(tp.Module):
def configure(self):
self.filename = self.get("filename")
def process(self, blob):
outfile = open(self.filename, "a")
outfile.write(f"{blob['pmt_id']} {blob['afterpulse_prob']}\n")
outfile.close()
return blob
class AfterpulsePlotter(tp.Module):
def configure(self):
self.file_path = self.get("file_path")
def process(self, blob):
fig, ax = plt.subplots(2, 2, figsize=(12, 5))
ax = ax.flatten()
ax[0].semilogy(blob["fit_info"]["x_ref"], blob["fit_info"]["y_ref"])
ax[0].semilogy(
blob["fit_info"]["x_ref"], blob["fit_info"]["prf_values_ref"]
)
ax[0].set_ylim(0.1, 1e4)
ax[0].set_xlabel("charge [A.U.]")
ax[0].set_ylabel("counts")
ax[1].semilogy(blob["fit_info"]["x"], blob["fit_info"]["y"])
ax[1].semilogy(blob["fit_info"]["x"], blob["fit_info"]["fit_values"])
ax[1].set_ylim(0.1, 1e4)
ax[1].set_xlabel("charge [A.U.]")
ax[1].set_ylabel("counts")
ax[1].text(0, 1e3, f"nphe: {round(blob['ap_nphe'], 2)}")
ax[2].hist(blob["ap_dist_us"], bins=200, log=True)
ax[2].set_xlabel("time [us]")
ax[2].set_ylabel("counts")
ax[2].text(
5,
2e3,
f"afterpulse probability: {round(blob['afterpulse_prob'], 2)}",
)
fig.savefig(f"{self.file_path}/{blob['pmt_id']}_afterpulse.png")
plt.close(fig)
return blob
| [
"os.mkdir",
"h5py.File",
"numpy.sum",
"numpy.argmax",
"os.path.basename",
"matplotlib.pyplot.close",
"numpy.allclose",
"scipy.optimize.curve_fit",
"collections.defaultdict",
"numpy.min",
"numpy.mean",
"numpy.array",
"numpy.linspace",
"scipy.interpolate.interp1d",
"matplotlib.pyplot.subpl... | [((1417, 1461), 'scipy.interpolate.interp1d', 'interp1d', (['phd_qe[0]', 'phd_qe[1]'], {'kind': '"""cubic"""'}), "(phd_qe[0], phd_qe[1], kind='cubic')\n", (1425, 1461), False, 'from scipy.interpolate import interp1d\n'), ((1725, 1752), 'numpy.allclose', 'np.allclose', (['wl_pmt', 'wl_phd'], {}), '(wl_pmt, wl_phd)\n', (1736, 1752), True, 'import numpy as np\n'), ((2802, 2826), 'h5py.File', 'h5py.File', (['filename', '"""r"""'], {}), "(filename, 'r')\n", (2811, 2826), False, 'import h5py\n'), ((3227, 3242), 'numpy.array', 'np.array', (['gains'], {}), '(gains)\n', (3235, 3242), True, 'import numpy as np\n'), ((3257, 3270), 'numpy.array', 'np.array', (['hvs'], {}), '(hvs)\n', (3265, 3270), True, 'import numpy as np\n'), ((3733, 3757), 'h5py.File', 'h5py.File', (['filename', '"""r"""'], {}), "(filename, 'r')\n", (3742, 3757), False, 'import h5py\n'), ((5887, 5929), 'numpy.linspace', 'np.linspace', (['(-5000000.0)', '(30000000.0)', '(10000)'], {}), '(-5000000.0, 30000000.0, 10000)\n', (5898, 5929), True, 'import numpy as np\n'), ((8783, 8802), 'numpy.mean', 'np.mean', (['rise_times'], {}), '(rise_times)\n', (8790, 8802), True, 'import numpy as np\n'), ((9693, 9720), 'numpy.min', 'np.min', (['zeroed_spes'], {'axis': '(1)'}), '(zeroed_spes, axis=1)\n', (9699, 9720), True, 'import numpy as np\n'), ((9758, 9781), 'numpy.mean', 'np.mean', (['spe_amplitudes'], {}), '(spe_amplitudes)\n', (9765, 9781), True, 'import numpy as np\n'), ((11386, 11440), 'scipy.optimize.curve_fit', 'curve_fit', (['gaussian', 'pre_x', 'pre_y'], {'p0': '[0, 100, 100000]'}), '(gaussian, pre_x, pre_y, p0=[0, 100, 100000])\n', (11395, 11440), False, 'from scipy.optimize import curve_fit\n'), ((11484, 11530), 'scipy.optimize.curve_fit', 'curve_fit', (['gaussian', 'x', 'y'], {'p0': '[0, 100, 100000]'}), '(gaussian, x, y, p0=[0, 100, 100000])\n', (11493, 11530), False, 'from scipy.optimize import curve_fit\n'), ((11637, 11696), 'numpy.sum', 'np.sum', (['charges[charges > popt[0] + popt[1] * self.n_sigma]'], {}), '(charges[charges > popt[0] + popt[1] * self.n_sigma])\n', (11643, 11696), True, 'import numpy as np\n'), ((11722, 11797), 'numpy.sum', 'np.sum', (['pre_charges[pre_charges > popt_pre[0] + popt_pre[1] * self.n_sigma]'], {}), '(pre_charges[pre_charges > popt_pre[0] + popt_pre[1] * self.n_sigma])\n', (11728, 11797), True, 'import numpy as np\n'), ((12584, 12601), 'collections.defaultdict', 'defaultdict', (['list'], {}), '(list)\n', (12595, 12601), False, 'from collections import defaultdict\n'), ((13900, 13917), 'collections.defaultdict', 'defaultdict', (['list'], {}), '(list)\n', (13911, 13917), False, 'from collections import defaultdict\n'), ((14796, 14820), 'os.mkdir', 'os.mkdir', (['self.file_path'], {}), '(self.file_path)\n', (14804, 14820), False, 'import os\n'), ((25207, 25319), 'numpy.sum', 'np.sum', (['((ap_dist_us > sig_pos_us + self.rel_ap_range[0]) & (ap_dist_us < \n sig_pos_us + self.rel_ap_range[1]))'], {}), '((ap_dist_us > sig_pos_us + self.rel_ap_range[0]) & (ap_dist_us < \n sig_pos_us + self.rel_ap_range[1]))\n', (25213, 25319), True, 'import numpy as np\n'), ((26037, 26072), 'matplotlib.pyplot.subplots', 'plt.subplots', (['(2)', '(2)'], {'figsize': '(12, 5)'}), '(2, 2, figsize=(12, 5))\n', (26049, 26072), True, 'import matplotlib.pyplot as plt\n'), ((27067, 27081), 'matplotlib.pyplot.close', 'plt.close', (['fig'], {}), '(fig)\n', (27076, 27081), True, 'import matplotlib.pyplot as plt\n'), ((6910, 6958), 'numpy.mean', 'np.mean', (["blob['waveforms'][signal_mask][:, :200]"], {}), "(blob['waveforms'][signal_mask][:, :200])\n", (6917, 6958), True, 'import numpy as np\n'), ((7410, 7422), 'numpy.argmax', 'np.argmax', (['n'], {}), '(n)\n', (7419, 7422), True, 'import numpy as np\n'), ((7462, 7513), 'scipy.optimize.curve_fit', 'curve_fit', (['gaussian', 't', 'n'], {'p0': '[mean_0, 2, 100000.0]'}), '(gaussian, t, n, p0=[mean_0, 2, 100000.0])\n', (7471, 7513), False, 'from scipy.optimize import curve_fit\n'), ((10829, 10855), 'numpy.mean', 'np.mean', (['waveforms'], {'axis': '(0)'}), '(waveforms, axis=0)\n', (10836, 10855), True, 'import numpy as np\n'), ((14916, 14952), 'matplotlib.pyplot.subplots', 'plt.subplots', (['(2)', '(2)'], {'figsize': '(16, 12)'}), '(2, 2, figsize=(16, 12))\n', (14928, 14952), True, 'import matplotlib.pyplot as plt\n'), ((19323, 19337), 'matplotlib.pyplot.close', 'plt.close', (['fig'], {}), '(fig)\n', (19332, 19337), True, 'import matplotlib.pyplot as plt\n'), ((21986, 22012), 'numpy.mean', 'np.mean', (['waveforms'], {'axis': '(0)'}), '(waveforms, axis=0)\n', (21993, 22012), True, 'import numpy as np\n'), ((2507, 2541), 'numpy.array', 'np.array', (["[blob['wl'], blob['qe']]"], {}), "([blob['wl'], blob['qe']])\n", (2515, 2541), True, 'import numpy as np\n'), ((3291, 3306), 'numpy.array', 'np.array', (['gains'], {}), '(gains)\n', (3299, 3306), True, 'import numpy as np\n'), ((7019, 7094), 'numpy.argmax', 'np.argmax', (["(zeroed_signals * blob['v_gain'] < self.voltage_threshold)"], {'axis': '(1)'}), "(zeroed_signals * blob['v_gain'] < self.voltage_threshold, axis=1)\n", (7028, 7094), True, 'import numpy as np\n'), ((9634, 9664), 'numpy.mean', 'np.mean', (['spes[:, :150]'], {'axis': '(1)'}), '(spes[:, :150], axis=1)\n', (9641, 9664), True, 'import numpy as np\n'), ((24186, 24221), 'numpy.mean', 'np.mean', (['waveforms[:, :100]'], {'axis': '(1)'}), '(waveforms[:, :100], axis=1)\n', (24193, 24221), True, 'import numpy as np\n'), ((24752, 24772), 'numpy.array', 'np.array', (['flat_peaks'], {}), '(flat_peaks)\n', (24760, 24772), True, 'import numpy as np\n'), ((25038, 25076), 'numpy.sum', 'np.sum', (['(ap_dist_us < sig_pos_us - 0.05)'], {}), '(ap_dist_us < sig_pos_us - 0.05)\n', (25044, 25076), True, 'import numpy as np\n'), ((3360, 3372), 'numpy.min', 'np.min', (['diff'], {}), '(diff)\n', (3366, 3372), True, 'import numpy as np\n'), ((19626, 19652), 'os.path.basename', 'os.path.basename', (['filename'], {}), '(filename)\n', (19642, 19652), False, 'import os\n')] |
from __future__ import print_function
import numpy as np
import regreg.api as rr
from ...tests.flags import SMALL_SAMPLES
from selection.api import (randomization,
split_glm_group_lasso)
from ...tests.instance import logistic_instance
from ...tests.decorators import (wait_for_return_value,
set_sampling_params_iftrue)
from ..glm import (standard_split_ci,
glm_nonparametric_bootstrap,
pairs_bootstrap_glm)
from ..M_estimator import restricted_Mest
from ..query import naive_confidence_intervals
@set_sampling_params_iftrue(SMALL_SAMPLES, ndraw=10, burnin=10)
@wait_for_return_value()
def test_split_compare(s=3,
n=200,
p=20,
signal=7,
rho=0.1,
split_frac=0.8,
lam_frac=0.7,
ndraw=10000, burnin=2000,
solve_args={'min_its':50, 'tol':1.e-10}, check_screen =True):
X, y, beta, _ = logistic_instance(n=n, p=p, s=s, rho=rho, signal=signal)
nonzero = np.where(beta)[0]
loss = rr.glm.logistic(X, y)
epsilon = 1.
lam = lam_frac * np.mean(np.fabs(np.dot(X.T, np.random.binomial(1, 1. / 2, (n, 10000)))).max(0))
W = np.ones(p)*lam
W[0] = 0 # use at least some unpenalized
penalty = rr.group_lasso(np.arange(p),
weights=dict(zip(np.arange(p), W)), lagrange=1.)
m = int(split_frac * n)
M_est = split_glm_group_lasso(loss, epsilon, m, penalty)
M_est.solve()
active_union = M_est.selection_variable['variables']
nactive = np.sum(active_union)
print("nactive", nactive)
if nactive==0:
return None
leftout_indices = M_est.randomized_loss.saturated_loss.case_weights == 0
screen = set(nonzero).issubset(np.nonzero(active_union)[0])
if check_screen and not screen:
return None
if True:
active_set = np.nonzero(active_union)[0]
true_vec = beta[active_union]
selected_features = np.zeros(p, np.bool)
selected_features[active_set] = True
unpenalized_mle = restricted_Mest(loss, selected_features)
form_covariances = glm_nonparametric_bootstrap(n, n)
target_info, target_observed = pairs_bootstrap_glm(M_est.loss, selected_features, inactive=None)
cov_info = M_est.setup_sampler()
target_cov, score_cov = form_covariances(target_info,
cross_terms=[cov_info],
nsample=M_est.nboot)
opt_sample = M_est.sampler.sample(ndraw,
burnin)
pivots = M_est.sampler.coefficient_pvalues(unpenalized_mle,
target_cov,
score_cov,
parameter=true_vec,
sample=opt_sample)
LU = intervals = M_est.sampler.confidence_intervals(unpenalized_mle, target_cov, score_cov, sample=opt_sample)
LU_naive = naive_confidence_intervals(np.diag(target_cov), target_observed)
if X.shape[0] - leftout_indices.sum() > nactive:
LU_split = standard_split_ci(rr.glm.logistic, X, y, active_union, leftout_indices)
else:
LU_split = np.ones((nactive, 2)) * np.nan
def coverage(LU):
L, U = LU[:,0], LU[:,1]
covered = np.zeros(nactive)
ci_length = np.zeros(nactive)
for j in range(nactive):
if check_screen:
if (L[j] <= true_vec[j]) and (U[j] >= true_vec[j]):
covered[j] = 1
else:
covered[j] = None
ci_length[j] = U[j]-L[j]
return covered, ci_length
covered, ci_length = coverage(LU)
covered_split, ci_length_split = coverage(LU_split)
covered_naive, ci_length_naive = coverage(LU_naive)
active_var = np.zeros(nactive, np.bool)
for j in range(nactive):
active_var[j] = active_set[j] in nonzero
return (pivots,
covered,
ci_length,
covered_split,
ci_length_split,
active_var,
covered_naive,
ci_length_naive)
| [
"numpy.sum",
"numpy.random.binomial",
"selection.api.split_glm_group_lasso",
"numpy.zeros",
"numpy.ones",
"numpy.nonzero",
"regreg.api.glm.logistic",
"numpy.where",
"numpy.arange",
"numpy.diag"
] | [((1176, 1197), 'regreg.api.glm.logistic', 'rr.glm.logistic', (['X', 'y'], {}), '(X, y)\n', (1191, 1197), True, 'import regreg.api as rr\n'), ((1548, 1596), 'selection.api.split_glm_group_lasso', 'split_glm_group_lasso', (['loss', 'epsilon', 'm', 'penalty'], {}), '(loss, epsilon, m, penalty)\n', (1569, 1596), False, 'from selection.api import randomization, split_glm_group_lasso\n'), ((1687, 1707), 'numpy.sum', 'np.sum', (['active_union'], {}), '(active_union)\n', (1693, 1707), True, 'import numpy as np\n'), ((1146, 1160), 'numpy.where', 'np.where', (['beta'], {}), '(beta)\n', (1154, 1160), True, 'import numpy as np\n'), ((1325, 1335), 'numpy.ones', 'np.ones', (['p'], {}), '(p)\n', (1332, 1335), True, 'import numpy as np\n'), ((1414, 1426), 'numpy.arange', 'np.arange', (['p'], {}), '(p)\n', (1423, 1426), True, 'import numpy as np\n'), ((2107, 2127), 'numpy.zeros', 'np.zeros', (['p', 'np.bool'], {}), '(p, np.bool)\n', (2115, 2127), True, 'import numpy as np\n'), ((4165, 4191), 'numpy.zeros', 'np.zeros', (['nactive', 'np.bool'], {}), '(nactive, np.bool)\n', (4173, 4191), True, 'import numpy as np\n'), ((1891, 1915), 'numpy.nonzero', 'np.nonzero', (['active_union'], {}), '(active_union)\n', (1901, 1915), True, 'import numpy as np\n'), ((2012, 2036), 'numpy.nonzero', 'np.nonzero', (['active_union'], {}), '(active_union)\n', (2022, 2036), True, 'import numpy as np\n'), ((3261, 3280), 'numpy.diag', 'np.diag', (['target_cov'], {}), '(target_cov)\n', (3268, 3280), True, 'import numpy as np\n'), ((3605, 3622), 'numpy.zeros', 'np.zeros', (['nactive'], {}), '(nactive)\n', (3613, 3622), True, 'import numpy as np\n'), ((3647, 3664), 'numpy.zeros', 'np.zeros', (['nactive'], {}), '(nactive)\n', (3655, 3664), True, 'import numpy as np\n'), ((3489, 3510), 'numpy.ones', 'np.ones', (['(nactive, 2)'], {}), '((nactive, 2))\n', (3496, 3510), True, 'import numpy as np\n'), ((1474, 1486), 'numpy.arange', 'np.arange', (['p'], {}), '(p)\n', (1483, 1486), True, 'import numpy as np\n'), ((1265, 1307), 'numpy.random.binomial', 'np.random.binomial', (['(1)', '(1.0 / 2)', '(n, 10000)'], {}), '(1, 1.0 / 2, (n, 10000))\n', (1283, 1307), True, 'import numpy as np\n')] |
import tiledb
import concurrent.futures
import progressbar
import numpy
from pathlib import Path
import pandas
array_uri = "/data/test/nyc_yellow_taxi_tiledb"
header_2016_2020 = [
"VendorID",
"tpep_pickup_datetime",
"tpep_dropoff_datetime",
"passenger_count",
"trip_distance",
"RatecodeID",
"store_and_fwd_flag",
"PULocationID",
"DOLocationID",
"payment_type",
"fare_amount",
"extra",
"mta_tax",
"tip_amount",
"tolls_amount",
"improvement_surcharge",
"total_amount",
]
header_2015 = [
# pickup_longitude,pickup_latitude
"VendorID",
"tpep_pickup_datetime",
"tpep_dropoff_datetime",
"passenger_count",
"trip_distance",
"pickup_longitude",
"pickup_latitude",
"RatecodeID",
"store_and_fwd_flag",
"dropoff_longitude",
"dropoff_latitude",
"payment_type",
"fare_amount",
"extra",
"mta_tax",
"tip_amount",
"tolls_amount",
"improvement_surcharge",
"total_amount",
]
dtypes = {
"VendorID": "float64",
# "tpep_pickup_datetime": "datetime64[ns]",
# "tpep_dropoff_datetime": "datetime64[ns]",
"passenger_count": "float64",
"trip_distance": "float64",
"RatecodeID": "float64",
"store_and_fwd_flag": "str",
# "PULocationID": "int64",
# "DOLocationID": "int64",
"payment_type": "float64",
"fare_amount": "float64",
"extra": "float64",
"mta_tax": "float64",
"tip_amount": "float64",
"tolls_amount": "float64",
"improvement_surcharge": "float64",
"total_amount": "float64",
}
converters = {
"PULocationID": lambda x: int(x) if x else None,
"DOLocationID": lambda x: int(x) if x else None,
}
def ingest_2015(array_uri, csv_file, taxi_zone_shapes):
vfs = tiledb.VFS()
csv_file = tiledb.FileIO(vfs, csv_file, mode="rb")
df = pandas.read_csv(
csv_file,
index_col=["tpep_pickup_datetime", "PULocationID"],
parse_dates=["tpep_dropoff_datetime", "tpep_pickup_datetime"],
skiprows=1,
names=header_2016_2020,
usecols=[i for i in range(len(header_2016_2020))],
dtype=dtypes,
# dtype={"store_and_fwd_flag": "bool"},
# usecols = [i for i in range(n)]
)
df["congestion_surcharge"] = numpy.float64(None)
tiledb.from_pandas(array_uri, df, mode="append", fillna={"store_and_fwd_flag": ""})
def ingest_2016(array_uri, csv_file):
vfs = tiledb.VFS()
csv_file = tiledb.FileIO(vfs, csv_file, mode="rb")
df = pandas.read_csv(
csv_file,
index_col=["tpep_pickup_datetime", "PULocationID"],
parse_dates=["tpep_dropoff_datetime", "tpep_pickup_datetime"],
skiprows=1,
names=header_2016_2020,
usecols=[i for i in range(len(header_2016_2020))],
dtype=dtypes,
# dtype={"store_and_fwd_flag": "bool"},
)
df["congestion_surcharge"] = numpy.float64(None)
tiledb.from_pandas(array_uri, df, mode="append", fillna={"store_and_fwd_flag": ""})
def create_array(array_uri):
schema = tiledb.ArraySchema(
domain=tiledb.Domain(
[
tiledb.Dim(
name="tpep_pickup_datetime",
domain=(
numpy.datetime64("1677-09-21T00:12:43.145224193"),
numpy.datetime64("2262-04-11T23:47:16.854774807"),
),
tile=None,
dtype="datetime64[ns]",
filters=tiledb.FilterList(
[
tiledb.ZstdFilter(level=-1),
]
),
),
tiledb.Dim(
name="PULocationID",
domain=(-9223372036854775808, 9223372036854774807),
tile=None,
dtype="int64",
filters=tiledb.FilterList(
[
tiledb.ZstdFilter(level=-1),
]
),
),
]
),
attrs=[
tiledb.Attr(
name="VendorID",
dtype="float64",
var=False,
nullable=False,
filters=tiledb.FilterList(
[
tiledb.ZstdFilter(level=-1),
]
),
),
tiledb.Attr(
name="tpep_dropoff_datetime",
dtype="datetime64[ns]",
var=False,
nullable=False,
filters=tiledb.FilterList(
[
tiledb.ZstdFilter(level=-1),
]
),
),
tiledb.Attr(
name="passenger_count",
dtype="float64",
var=False,
nullable=False,
filters=tiledb.FilterList(
[
tiledb.ZstdFilter(level=-1),
]
),
),
tiledb.Attr(
name="trip_distance",
dtype="float64",
var=False,
nullable=False,
filters=tiledb.FilterList(
[
tiledb.ZstdFilter(level=-1),
]
),
),
tiledb.Attr(
name="RatecodeID",
dtype="float64",
var=False,
nullable=False,
filters=tiledb.FilterList(
[
tiledb.ZstdFilter(level=-1),
]
),
),
tiledb.Attr(
name="store_and_fwd_flag",
dtype="ascii",
var=True,
nullable=False,
filters=tiledb.FilterList(
[
tiledb.ZstdFilter(level=-1),
]
),
),
tiledb.Attr(
name="DOLocationID",
dtype="int64",
var=False,
nullable=False,
filters=tiledb.FilterList(
[
tiledb.ZstdFilter(level=-1),
]
),
),
tiledb.Attr(
name="payment_type",
dtype="float64",
var=False,
nullable=False,
filters=tiledb.FilterList(
[
tiledb.ZstdFilter(level=-1),
]
),
),
tiledb.Attr(
name="fare_amount",
dtype="float64",
var=False,
nullable=False,
filters=tiledb.FilterList(
[
tiledb.ZstdFilter(level=-1),
]
),
),
tiledb.Attr(
name="extra",
dtype="float64",
var=False,
nullable=False,
filters=tiledb.FilterList(
[
tiledb.ZstdFilter(level=-1),
]
),
),
tiledb.Attr(
name="mta_tax",
dtype="float64",
var=False,
nullable=False,
filters=tiledb.FilterList(
[
tiledb.ZstdFilter(level=-1),
]
),
),
tiledb.Attr(
name="tip_amount",
dtype="float64",
var=False,
nullable=False,
filters=tiledb.FilterList(
[
tiledb.ZstdFilter(level=-1),
]
),
),
tiledb.Attr(
name="tolls_amount",
dtype="float64",
var=False,
nullable=False,
filters=tiledb.FilterList(
[
tiledb.ZstdFilter(level=-1),
]
),
),
tiledb.Attr(
name="improvement_surcharge",
dtype="float64",
var=False,
nullable=False,
filters=tiledb.FilterList(
[
tiledb.ZstdFilter(level=-1),
]
),
),
tiledb.Attr(
name="total_amount",
dtype="float64",
var=False,
nullable=False,
filters=tiledb.FilterList(
[
tiledb.ZstdFilter(level=-1),
]
),
),
tiledb.Attr(
name="congestion_surcharge",
dtype="float64",
var=False,
nullable=False,
filters=tiledb.FilterList(
[
tiledb.ZstdFilter(level=-1),
]
),
),
],
cell_order="hilbert",
# tile_order="hilbert",
capacity=100000,
sparse=True,
allows_duplicates=True,
coords_filters=tiledb.FilterList([tiledb.ZstdFilter(level=-1)]),
)
if not (tiledb.VFS().is_dir(array_uri)):
tiledb.Array.create(array_uri, schema)
def list_data():
files = tiledb.VFS().ls("s3://nyc-tlc/trip data/")
files_with_schema_version = {}
for f in files:
if not f.startswith("s3://nyc-tlc/trip data/yellow_tripdata_"):
continue
filename = Path(f).stem
year_month = filename.split("_")[2]
year = int(year_month.split("-")[0])
month = int(year_month.split("-")[1])
if (year) >= 2019:
files_with_schema_version[f] = "2019"
elif (year == 2016 and month >= 7) or year == 2017 or year == 2018:
files_with_schema_version[f] = "2016"
elif year == 2015 or (year == 2016 and month < 7):
files_with_schema_version[f] = "2015"
elif year < 2015:
files_with_schema_version[f] = "2009"
return files_with_schema_version
def load_data(array_uri, files_with_schema_version):
futures = []
# max_workers=len(yellow_tripdata_2019_schema)
with concurrent.futures.ProcessPoolExecutor() as executor:
for csv_file in files_with_schema_version.items():
if csv_file[1] == "2019":
print(f"ingestion 2019 schema file {csv_file[0]} directly")
futures.append(
executor.submit(
tiledb.from_csv,
array_uri,
csv_file[0],
mode="append",
index_col=["tpep_pickup_datetime", "PULocationID"],
parse_dates=["tpep_dropoff_datetime", "tpep_pickup_datetime"],
fillna={"store_and_fwd_flag": ""},
# dtype={"store_and_fwd_flag": "bool"},
)
)
elif csv_file[1] == "2016":
print(
f"ingestion 2016 schema file {csv_file[0]} by adding null congestion"
)
futures.append(executor.submit(ingest_2016, array_uri, csv_file[0]))
elif csv_file[1] == "2015":
print(f"Skipping 2015 formatted file {csv_file[0]} for now")
elif csv_file[1] == "2009":
print(f"Skipping 2009 formatted file {csv_file[0]} for now")
else:
raise RuntimeError(f"Unknown csv schema version {csv_file[1]}")
for future in progressbar.progressbar(futures):
result = future.result()
def main():
create_array(array_uri)
files_with_schema_version = list_data()
load_data(array_uri, files_with_schema_version)
if __name__ == "__main__":
main()
| [
"tiledb.from_pandas",
"numpy.datetime64",
"progressbar.progressbar",
"tiledb.Array.create",
"tiledb.VFS",
"pathlib.Path",
"tiledb.ZstdFilter",
"numpy.float64",
"tiledb.FileIO"
] | [((1769, 1781), 'tiledb.VFS', 'tiledb.VFS', ([], {}), '()\n', (1779, 1781), False, 'import tiledb\n'), ((1797, 1836), 'tiledb.FileIO', 'tiledb.FileIO', (['vfs', 'csv_file'], {'mode': '"""rb"""'}), "(vfs, csv_file, mode='rb')\n", (1810, 1836), False, 'import tiledb\n'), ((2274, 2293), 'numpy.float64', 'numpy.float64', (['None'], {}), '(None)\n', (2287, 2293), False, 'import numpy\n'), ((2299, 2387), 'tiledb.from_pandas', 'tiledb.from_pandas', (['array_uri', 'df'], {'mode': '"""append"""', 'fillna': "{'store_and_fwd_flag': ''}"}), "(array_uri, df, mode='append', fillna={\n 'store_and_fwd_flag': ''})\n", (2317, 2387), False, 'import tiledb\n'), ((2433, 2445), 'tiledb.VFS', 'tiledb.VFS', ([], {}), '()\n', (2443, 2445), False, 'import tiledb\n'), ((2461, 2500), 'tiledb.FileIO', 'tiledb.FileIO', (['vfs', 'csv_file'], {'mode': '"""rb"""'}), "(vfs, csv_file, mode='rb')\n", (2474, 2500), False, 'import tiledb\n'), ((2896, 2915), 'numpy.float64', 'numpy.float64', (['None'], {}), '(None)\n', (2909, 2915), False, 'import numpy\n'), ((2920, 3008), 'tiledb.from_pandas', 'tiledb.from_pandas', (['array_uri', 'df'], {'mode': '"""append"""', 'fillna': "{'store_and_fwd_flag': ''}"}), "(array_uri, df, mode='append', fillna={\n 'store_and_fwd_flag': ''})\n", (2938, 3008), False, 'import tiledb\n'), ((9660, 9698), 'tiledb.Array.create', 'tiledb.Array.create', (['array_uri', 'schema'], {}), '(array_uri, schema)\n', (9679, 9698), False, 'import tiledb\n'), ((12033, 12065), 'progressbar.progressbar', 'progressbar.progressbar', (['futures'], {}), '(futures)\n', (12056, 12065), False, 'import progressbar\n'), ((9730, 9742), 'tiledb.VFS', 'tiledb.VFS', ([], {}), '()\n', (9740, 9742), False, 'import tiledb\n'), ((9941, 9948), 'pathlib.Path', 'Path', (['f'], {}), '(f)\n', (9945, 9948), False, 'from pathlib import Path\n'), ((9619, 9631), 'tiledb.VFS', 'tiledb.VFS', ([], {}), '()\n', (9629, 9631), False, 'import tiledb\n'), ((9569, 9596), 'tiledb.ZstdFilter', 'tiledb.ZstdFilter', ([], {'level': '(-1)'}), '(level=-1)\n', (9586, 9596), False, 'import tiledb\n'), ((3243, 3292), 'numpy.datetime64', 'numpy.datetime64', (['"""1677-09-21T00:12:43.145224193"""'], {}), "('1677-09-21T00:12:43.145224193')\n", (3259, 3292), False, 'import numpy\n'), ((3318, 3367), 'numpy.datetime64', 'numpy.datetime64', (['"""2262-04-11T23:47:16.854774807"""'], {}), "('2262-04-11T23:47:16.854774807')\n", (3334, 3367), False, 'import numpy\n'), ((4350, 4377), 'tiledb.ZstdFilter', 'tiledb.ZstdFilter', ([], {'level': '(-1)'}), '(level=-1)\n', (4367, 4377), False, 'import tiledb\n'), ((4694, 4721), 'tiledb.ZstdFilter', 'tiledb.ZstdFilter', ([], {'level': '(-1)'}), '(level=-1)\n', (4711, 4721), False, 'import tiledb\n'), ((5025, 5052), 'tiledb.ZstdFilter', 'tiledb.ZstdFilter', ([], {'level': '(-1)'}), '(level=-1)\n', (5042, 5052), False, 'import tiledb\n'), ((5354, 5381), 'tiledb.ZstdFilter', 'tiledb.ZstdFilter', ([], {'level': '(-1)'}), '(level=-1)\n', (5371, 5381), False, 'import tiledb\n'), ((5680, 5707), 'tiledb.ZstdFilter', 'tiledb.ZstdFilter', ([], {'level': '(-1)'}), '(level=-1)\n', (5697, 5707), False, 'import tiledb\n'), ((6011, 6038), 'tiledb.ZstdFilter', 'tiledb.ZstdFilter', ([], {'level': '(-1)'}), '(level=-1)\n', (6028, 6038), False, 'import tiledb\n'), ((6337, 6364), 'tiledb.ZstdFilter', 'tiledb.ZstdFilter', ([], {'level': '(-1)'}), '(level=-1)\n', (6354, 6364), False, 'import tiledb\n'), ((6665, 6692), 'tiledb.ZstdFilter', 'tiledb.ZstdFilter', ([], {'level': '(-1)'}), '(level=-1)\n', (6682, 6692), False, 'import tiledb\n'), ((6992, 7019), 'tiledb.ZstdFilter', 'tiledb.ZstdFilter', ([], {'level': '(-1)'}), '(level=-1)\n', (7009, 7019), False, 'import tiledb\n'), ((7313, 7340), 'tiledb.ZstdFilter', 'tiledb.ZstdFilter', ([], {'level': '(-1)'}), '(level=-1)\n', (7330, 7340), False, 'import tiledb\n'), ((7636, 7663), 'tiledb.ZstdFilter', 'tiledb.ZstdFilter', ([], {'level': '(-1)'}), '(level=-1)\n', (7653, 7663), False, 'import tiledb\n'), ((7962, 7989), 'tiledb.ZstdFilter', 'tiledb.ZstdFilter', ([], {'level': '(-1)'}), '(level=-1)\n', (7979, 7989), False, 'import tiledb\n'), ((8290, 8317), 'tiledb.ZstdFilter', 'tiledb.ZstdFilter', ([], {'level': '(-1)'}), '(level=-1)\n', (8307, 8317), False, 'import tiledb\n'), ((8627, 8654), 'tiledb.ZstdFilter', 'tiledb.ZstdFilter', ([], {'level': '(-1)'}), '(level=-1)\n', (8644, 8654), False, 'import tiledb\n'), ((8955, 8982), 'tiledb.ZstdFilter', 'tiledb.ZstdFilter', ([], {'level': '(-1)'}), '(level=-1)\n', (8972, 8982), False, 'import tiledb\n'), ((9291, 9318), 'tiledb.ZstdFilter', 'tiledb.ZstdFilter', ([], {'level': '(-1)'}), '(level=-1)\n', (9308, 9318), False, 'import tiledb\n'), ((3568, 3595), 'tiledb.ZstdFilter', 'tiledb.ZstdFilter', ([], {'level': '(-1)'}), '(level=-1)\n', (3585, 3595), False, 'import tiledb\n'), ((3973, 4000), 'tiledb.ZstdFilter', 'tiledb.ZstdFilter', ([], {'level': '(-1)'}), '(level=-1)\n', (3990, 4000), False, 'import tiledb\n')] |
#!/usr/bin/env python
# coding=utf-8
"""
Script to analyse domestic hot water profiles.
Based on Annex 42 Substask A --> Assumtion for Germany:
Around 64 Liters hot water per occupant and day (35 Kelvin temperatur split)
--> 2.6 kWh / person and day
Based on Canadian survey
http://www.sciencedirect.com/science/article/pii/S0378778812006238
Nb occupants - DHW volume per capita and day in liters
1 - 139
2 - 84
3 - 67
4 - 60
5 - 59
6 - 58
Mean - 65
No information on temperature split. However, 494 liters oil consumption
for dhw per year (on person apartment). --> Assuming lower caloric value
of 10 kWh/liter --> 13.5 kWh/day and person (for DHW)
--> Theoretically 84 Kelvin
Temperatur split (kind of high).
--> DHW volumes might be realistic for German citizens, however,
temperature-split should be reduced
"""
import numpy as np
import matplotlib.pyplot as plt
import pycity_base.classes.demand.DomesticHotWater as DomesticHotWater
import pycity_base.classes.demand.Occupancy as occ
import pycity_base.classes.Weather as Weather
import pycity_base.functions.changeResolution as chres
import pycity_calc.environments.co2emissions as co2
import pycity_calc.environments.environment as env
import pycity_calc.environments.market as mark
import pycity_calc.environments.timer as time
import pycity_calc.toolbox.dimensioning.dim_functions as dimfunc
def set_up_environment(timestep):
"""
Generate environment object
Parameters
----------
timestep : int
Timestep in seconds
Returns
-------
environment : object
Environment of pycity_calc
"""
year = 2010
location = (51.529086, 6.944689) # (latitude, longitute) of Bottrop
altitude = 55 # Altitude of Bottrop
# Generate timer object
timer = time.TimerExtended(timestep=timestep, year=year)
# Generate weather object
weather = Weather.Weather(timer, useTRY=True, location=location,
altitude=altitude)
# Generate market object
market = mark.Market()
# Generate co2 emissions object
co2em = co2.Emissions(year=year)
# Generate environment
environment = env.EnvironmentExtended(timer, weather, prices=market,
location=location, co2em=co2em)
return environment
def run_dhw_analysis_annex42(environment):
timestep = environment.timer.timeDiscretization
temp_flow = 60
return_flow = 25
print('Analysis of profile with 1 person and 140 liters dhw per day.')
print('Temperature split is 35 Kelvin')
print('##############################################################')
dhw_annex42 = DomesticHotWater.DomesticHotWater(environment,
tFlow=temp_flow,
thermal=True,
method=1, # Annex 42
dailyConsumption=140,
supplyTemperature=
return_flow)
results = dhw_annex42.get_power(currentValues=False)
print('Results for Annex42 profile:')
print()
print("Thermal power in Watt: " + str(results[0]))
print("Required flow temperature in degree Celsius: " + str(results[1]))
print()
# Convert into energy values in kWh
dhw_energy_curve = results[0] * timestep / (3600 * 1000)
annual_energy_demand = np.sum(dhw_energy_curve)
print('Annual dhw energy demand in kWh: ', annual_energy_demand)
print()
print('DHW energy demand in kWh / person and day: ',
annual_energy_demand / 365)
print()
max_p = dimfunc.get_max_p_of_power_curve(results[0])
print('Maximal thermal power in kW: ', max_p / 1000)
av_p = annual_energy_demand / (365*24) # in kW
print('Average thermal power in kW: ', av_p)
index_max = np.argmax(results[0])
print('Index (minute) of maximal power: ', index_max)
plt.plot(np.arange(365 * 24 * 3600 / timestep), dhw_annex42.loadcurve)
plt.ylabel("Heat demand in Watt")
plt.xlim((0, 8760))
plt.show()
print('##############################################################')
print('Analysis of profile with 3 person and 67 * 3 liters dhw per day.')
print('Temperature split is 35 Kelvin')
print('##############################################################')
nb_persons = 3
dhw_total = 67 * nb_persons
dhw_annex42 = DomesticHotWater.DomesticHotWater(environment,
tFlow=temp_flow,
thermal=True,
method=1, # Annex 42
dailyConsumption=dhw_total,
supplyTemperature=
return_flow)
results = dhw_annex42.get_power(currentValues=False)
print('Results for Annex42 profile:')
print()
print("Thermal power in Watt: " + str(results[0]))
print("Required flow temperature in degree Celsius: " + str(results[1]))
print()
# Convert into energy values in kWh
dhw_energy_curve = results[0] * timestep / (3600 * 1000)
annual_energy_demand = np.sum(dhw_energy_curve)
print('Annual dhw energy demand in kWh: ', annual_energy_demand)
print()
print('DHW energy demand in kWh / person and day: ',
annual_energy_demand / (365 * nb_persons))
print()
max_p = dimfunc.get_max_p_of_power_curve(results[0])
print('Maximal thermal power in kW: ', max_p / 1000)
av_p = annual_energy_demand / (365*24) # in kW
print('Average thermal power in kW: ', av_p)
index_max = np.argmax(results[0])
print('Index (minute) of maximal power: ', index_max)
plt.plot(np.arange(365 * 24 * 3600 / timestep), dhw_annex42.loadcurve)
plt.ylabel("Heat demand in Watt")
plt.xlim((0, 8760))
plt.show()
print('##############################################################')
print('Analysis of profile with 5 person and 59 * 3 liters dhw per day.')
print('Temperature split is 35 Kelvin')
print('##############################################################')
nb_persons = 5
dhw_total = 59 * nb_persons
dhw_annex42 = DomesticHotWater.DomesticHotWater(environment,
tFlow=temp_flow,
thermal=True,
method=1, # Annex 42
dailyConsumption=dhw_total,
supplyTemperature=
return_flow)
results = dhw_annex42.get_power(currentValues=False)
print('Results for Annex42 profile:')
print()
print("Thermal power in Watt: " + str(results[0]))
print("Required flow temperature in degree Celsius: " + str(results[1]))
print()
# Convert into energy values in kWh
dhw_energy_curve = results[0] * timestep / (3600 * 1000)
annual_energy_demand = np.sum(dhw_energy_curve)
print('Annual dhw energy demand in kWh: ', annual_energy_demand)
print()
print('DHW energy demand in kWh / person and day: ',
annual_energy_demand / (365 * nb_persons))
print()
max_p = dimfunc.get_max_p_of_power_curve(results[0])
print('Maximal thermal power in kW: ', max_p / 1000)
av_p = annual_energy_demand / (365*24) # in kW
print('Average thermal power in kW: ', av_p)
index_max = np.argmax(results[0])
print('Index (minute) of maximal power: ', index_max)
plt.plot(np.arange(365 * 24 * 3600 / timestep), dhw_annex42.loadcurve)
plt.ylabel("Heat demand in Watt")
plt.xlim((0, 8760))
plt.show()
print('##############################################################')
def run_analysis_dhw_stochastical(environment):
timestep = environment.timer.timeDiscretization
t_flow = 60
t_back = 20
# Generate different occupancy profiles
occupancy_object1 = occ.Occupancy(environment, number_occupants=1)
occupancy_object3 = occ.Occupancy(environment, number_occupants=3)
occupancy_object5 = occ.Occupancy(environment, number_occupants=5)
# Generate dhw profile for 1 person
dhw_stochastical = DomesticHotWater.DomesticHotWater(environment,
tFlow=t_flow,
thermal=True,
method=2,
supplyTemperature=
t_back,
occupancy=
occupancy_object1.
occupancy)
dhw_power_curve = dhw_stochastical.get_power(currentValues=False,
returnTemperature=False)
# Convert into energy values in kWh
dhw_energy_curve = dhw_power_curve * timestep / (3600 * 1000)
annual_energy_demand = np.sum(dhw_energy_curve)
# DHW volume flow curve in liters/hour
volume_flow_curve = dhw_stochastical.water
# Recalc into water volume in liters
water_volume_per_timestep = volume_flow_curve / 3600 * timestep
# Average daily dhw consumption in liters
av_daily_dhw_volume = np.sum(water_volume_per_timestep) / 365
occ_profile = occupancy_object1.occupancy
print('Results for stochastic DHW profile:\n')
print('Max number of occupants:', max(occ_profile))
print('Annual dhw energy demand in kWh: ', annual_energy_demand)
print('Average daily domestic hot water volume in liters:',
av_daily_dhw_volume)
max_p = dimfunc.get_max_p_of_power_curve(dhw_power_curve)
print('Maximal thermal power in kW: ', max_p / 1000)
av_p = annual_energy_demand / (365*24) # in kW
print('Average thermal power in kW: ', av_p)
ax1 = plt.subplot(2, 1, 1)
plt.step(np.arange(365 * 24 * 3600 / timestep),
dhw_stochastical.loadcurve, linewidth=2)
plt.ylabel("Heat demand in Watt")
plt.xlim((0, 8760))
occ_profile_chres = chres.changeResolution(occ_profile, 600, timestep)
plt.subplot(2, 1, 2, sharex=ax1)
plt.step(np.arange(365 * 24 * 3600 / timestep), occ_profile_chres,
linewidth=2)
plt.ylabel("Active occupants")
offset = 0.2
plt.ylim((-offset, max(occ_profile) + offset))
plt.yticks(list(range(int(max(occ_profile) + 1))))
plt.show()
print('############################################################')
# Generate dhw profile for 1 person
dhw_stochastical = DomesticHotWater.DomesticHotWater(environment,
tFlow=t_flow,
thermal=True,
method=2,
supplyTemperature=
t_back,
occupancy=
occupancy_object3.
occupancy)
dhw_power_curve = dhw_stochastical.get_power(currentValues=False,
returnTemperature=False)
# Convert into energy values in kWh
dhw_energy_curve = dhw_power_curve * timestep / (3600 * 1000)
annual_energy_demand = np.sum(dhw_energy_curve)
# DHW volume flow curve in liters/hour
volume_flow_curve = dhw_stochastical.water
# Recalc into water volume in liters
water_volume_per_timestep = volume_flow_curve / 3600 * timestep
# Average daily dhw consumption in liters
av_daily_dhw_volume = np.sum(water_volume_per_timestep) / 365
occ_profile = occupancy_object3.occupancy
print('Results for stochastic DHW profile:\n')
print('Max number of occupants:', max(occ_profile))
print('Annual dhw energy demand in kWh: ', annual_energy_demand)
print('Average daily domestic hot water volume in liters:',
av_daily_dhw_volume)
max_p = dimfunc.get_max_p_of_power_curve(dhw_power_curve)
print('Maximal thermal power in kW: ', max_p / 1000)
av_p = annual_energy_demand / (365*24) # in kW
print('Average thermal power in kW: ', av_p)
ax1 = plt.subplot(2, 1, 1)
plt.step(np.arange(365 * 24 * 3600 / timestep),
dhw_stochastical.loadcurve, linewidth=2)
plt.ylabel("Heat demand in Watt")
plt.xlim((0, 8760))
occ_profile_chres = chres.changeResolution(occ_profile, 600, timestep)
plt.subplot(2, 1, 2, sharex=ax1)
plt.step(np.arange(365 * 24 * 3600 / timestep), occ_profile_chres,
linewidth=2)
plt.ylabel("Active occupants")
offset = 0.2
plt.ylim((-offset, max(occ_profile) + offset))
plt.yticks(list(range(int(max(occ_profile) + 1))))
plt.show()
print('############################################################')
# Generate dhw profile for 1 person
dhw_stochastical = DomesticHotWater.DomesticHotWater(environment,
tFlow=t_flow,
thermal=True,
method=2,
supplyTemperature=
t_back,
occupancy=
occupancy_object5.
occupancy)
dhw_power_curve = dhw_stochastical.get_power(currentValues=False,
returnTemperature=False)
# Convert into energy values in kWh
dhw_energy_curve = dhw_power_curve * timestep / (3600 * 1000)
annual_energy_demand = np.sum(dhw_energy_curve)
# DHW volume flow curve in liters/hour
volume_flow_curve = dhw_stochastical.water
# Recalc into water volume in liters
water_volume_per_timestep = volume_flow_curve / 3600 * timestep
# Average daily dhw consumption in liters
av_daily_dhw_volume = np.sum(water_volume_per_timestep) / 365
occ_profile = occupancy_object5.occupancy
print('Results for stochastic DHW profile:\n')
print('Max number of occupants:', max(occ_profile))
print('Annual dhw energy demand in kWh: ', annual_energy_demand)
print('Average daily domestic hot water volume in liters:',
av_daily_dhw_volume)
max_p = dimfunc.get_max_p_of_power_curve(dhw_power_curve)
print('Maximal thermal power in kW: ', max_p / 1000)
av_p = annual_energy_demand / (365*24) # in kW
print('Average thermal power in kW: ', av_p)
ax1 = plt.subplot(2, 1, 1)
plt.step(np.arange(365 * 24 * 3600 / timestep),
dhw_stochastical.loadcurve, linewidth=2)
plt.ylabel("Heat demand in Watt")
plt.xlim((0, 8760))
occ_profile_chres = chres.changeResolution(occ_profile, 600, timestep)
plt.subplot(2, 1, 2, sharex=ax1)
plt.step(np.arange(365 * 24 * 3600 / timestep), occ_profile_chres,
linewidth=2)
plt.ylabel("Active occupants")
offset = 0.2
plt.ylim((-offset, max(occ_profile) + offset))
plt.yticks(list(range(int(max(occ_profile) + 1))))
plt.show()
print('############################################################')
if __name__ == '__main__':
# Generate environment
environment = set_up_environment(timestep=900)
# Run program for Annex 42 profiles
run_dhw_analysis_annex42(environment)
# Generate environment
environment = set_up_environment(timestep=60)
# Run analysis for stochastical dhw profiles
run_analysis_dhw_stochastical(environment)
| [
"matplotlib.pyplot.xlim",
"matplotlib.pyplot.subplot",
"pycity_base.functions.changeResolution.changeResolution",
"pycity_calc.environments.timer.TimerExtended",
"numpy.sum",
"pycity_base.classes.demand.DomesticHotWater.DomesticHotWater",
"numpy.argmax",
"matplotlib.pyplot.show",
"pycity_calc.toolbo... | [((1779, 1827), 'pycity_calc.environments.timer.TimerExtended', 'time.TimerExtended', ([], {'timestep': 'timestep', 'year': 'year'}), '(timestep=timestep, year=year)\n', (1797, 1827), True, 'import pycity_calc.environments.timer as time\n'), ((1874, 1947), 'pycity_base.classes.Weather.Weather', 'Weather.Weather', (['timer'], {'useTRY': '(True)', 'location': 'location', 'altitude': 'altitude'}), '(timer, useTRY=True, location=location, altitude=altitude)\n', (1889, 1947), True, 'import pycity_base.classes.Weather as Weather\n'), ((2022, 2035), 'pycity_calc.environments.market.Market', 'mark.Market', ([], {}), '()\n', (2033, 2035), True, 'import pycity_calc.environments.market as mark\n'), ((2086, 2110), 'pycity_calc.environments.co2emissions.Emissions', 'co2.Emissions', ([], {'year': 'year'}), '(year=year)\n', (2099, 2110), True, 'import pycity_calc.environments.co2emissions as co2\n'), ((2158, 2248), 'pycity_calc.environments.environment.EnvironmentExtended', 'env.EnvironmentExtended', (['timer', 'weather'], {'prices': 'market', 'location': 'location', 'co2em': 'co2em'}), '(timer, weather, prices=market, location=location,\n co2em=co2em)\n', (2181, 2248), True, 'import pycity_calc.environments.environment as env\n'), ((2664, 2809), 'pycity_base.classes.demand.DomesticHotWater.DomesticHotWater', 'DomesticHotWater.DomesticHotWater', (['environment'], {'tFlow': 'temp_flow', 'thermal': '(True)', 'method': '(1)', 'dailyConsumption': '(140)', 'supplyTemperature': 'return_flow'}), '(environment, tFlow=temp_flow, thermal=\n True, method=1, dailyConsumption=140, supplyTemperature=return_flow)\n', (2697, 2809), True, 'import pycity_base.classes.demand.DomesticHotWater as DomesticHotWater\n'), ((3517, 3541), 'numpy.sum', 'np.sum', (['dhw_energy_curve'], {}), '(dhw_energy_curve)\n', (3523, 3541), True, 'import numpy as np\n'), ((3745, 3789), 'pycity_calc.toolbox.dimensioning.dim_functions.get_max_p_of_power_curve', 'dimfunc.get_max_p_of_power_curve', (['results[0]'], {}), '(results[0])\n', (3777, 3789), True, 'import pycity_calc.toolbox.dimensioning.dim_functions as dimfunc\n'), ((3966, 3987), 'numpy.argmax', 'np.argmax', (['results[0]'], {}), '(results[0])\n', (3975, 3987), True, 'import numpy as np\n'), ((4126, 4159), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Heat demand in Watt"""'], {}), "('Heat demand in Watt')\n", (4136, 4159), True, 'import matplotlib.pyplot as plt\n'), ((4164, 4183), 'matplotlib.pyplot.xlim', 'plt.xlim', (['(0, 8760)'], {}), '((0, 8760))\n', (4172, 4183), True, 'import matplotlib.pyplot as plt\n'), ((4188, 4198), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (4196, 4198), True, 'import matplotlib.pyplot as plt\n'), ((4546, 4697), 'pycity_base.classes.demand.DomesticHotWater.DomesticHotWater', 'DomesticHotWater.DomesticHotWater', (['environment'], {'tFlow': 'temp_flow', 'thermal': '(True)', 'method': '(1)', 'dailyConsumption': 'dhw_total', 'supplyTemperature': 'return_flow'}), '(environment, tFlow=temp_flow, thermal=\n True, method=1, dailyConsumption=dhw_total, supplyTemperature=return_flow)\n', (4579, 4697), True, 'import pycity_base.classes.demand.DomesticHotWater as DomesticHotWater\n'), ((5405, 5429), 'numpy.sum', 'np.sum', (['dhw_energy_curve'], {}), '(dhw_energy_curve)\n', (5411, 5429), True, 'import numpy as np\n'), ((5648, 5692), 'pycity_calc.toolbox.dimensioning.dim_functions.get_max_p_of_power_curve', 'dimfunc.get_max_p_of_power_curve', (['results[0]'], {}), '(results[0])\n', (5680, 5692), True, 'import pycity_calc.toolbox.dimensioning.dim_functions as dimfunc\n'), ((5869, 5890), 'numpy.argmax', 'np.argmax', (['results[0]'], {}), '(results[0])\n', (5878, 5890), True, 'import numpy as np\n'), ((6029, 6062), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Heat demand in Watt"""'], {}), "('Heat demand in Watt')\n", (6039, 6062), True, 'import matplotlib.pyplot as plt\n'), ((6067, 6086), 'matplotlib.pyplot.xlim', 'plt.xlim', (['(0, 8760)'], {}), '((0, 8760))\n', (6075, 6086), True, 'import matplotlib.pyplot as plt\n'), ((6091, 6101), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (6099, 6101), True, 'import matplotlib.pyplot as plt\n'), ((6449, 6600), 'pycity_base.classes.demand.DomesticHotWater.DomesticHotWater', 'DomesticHotWater.DomesticHotWater', (['environment'], {'tFlow': 'temp_flow', 'thermal': '(True)', 'method': '(1)', 'dailyConsumption': 'dhw_total', 'supplyTemperature': 'return_flow'}), '(environment, tFlow=temp_flow, thermal=\n True, method=1, dailyConsumption=dhw_total, supplyTemperature=return_flow)\n', (6482, 6600), True, 'import pycity_base.classes.demand.DomesticHotWater as DomesticHotWater\n'), ((7308, 7332), 'numpy.sum', 'np.sum', (['dhw_energy_curve'], {}), '(dhw_energy_curve)\n', (7314, 7332), True, 'import numpy as np\n'), ((7550, 7594), 'pycity_calc.toolbox.dimensioning.dim_functions.get_max_p_of_power_curve', 'dimfunc.get_max_p_of_power_curve', (['results[0]'], {}), '(results[0])\n', (7582, 7594), True, 'import pycity_calc.toolbox.dimensioning.dim_functions as dimfunc\n'), ((7771, 7792), 'numpy.argmax', 'np.argmax', (['results[0]'], {}), '(results[0])\n', (7780, 7792), True, 'import numpy as np\n'), ((7931, 7964), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Heat demand in Watt"""'], {}), "('Heat demand in Watt')\n", (7941, 7964), True, 'import matplotlib.pyplot as plt\n'), ((7969, 7988), 'matplotlib.pyplot.xlim', 'plt.xlim', (['(0, 8760)'], {}), '((0, 8760))\n', (7977, 7988), True, 'import matplotlib.pyplot as plt\n'), ((7993, 8003), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (8001, 8003), True, 'import matplotlib.pyplot as plt\n'), ((8287, 8333), 'pycity_base.classes.demand.Occupancy.Occupancy', 'occ.Occupancy', (['environment'], {'number_occupants': '(1)'}), '(environment, number_occupants=1)\n', (8300, 8333), True, 'import pycity_base.classes.demand.Occupancy as occ\n'), ((8358, 8404), 'pycity_base.classes.demand.Occupancy.Occupancy', 'occ.Occupancy', (['environment'], {'number_occupants': '(3)'}), '(environment, number_occupants=3)\n', (8371, 8404), True, 'import pycity_base.classes.demand.Occupancy as occ\n'), ((8429, 8475), 'pycity_base.classes.demand.Occupancy.Occupancy', 'occ.Occupancy', (['environment'], {'number_occupants': '(5)'}), '(environment, number_occupants=5)\n', (8442, 8475), True, 'import pycity_base.classes.demand.Occupancy as occ\n'), ((8541, 8694), 'pycity_base.classes.demand.DomesticHotWater.DomesticHotWater', 'DomesticHotWater.DomesticHotWater', (['environment'], {'tFlow': 't_flow', 'thermal': '(True)', 'method': '(2)', 'supplyTemperature': 't_back', 'occupancy': 'occupancy_object1.occupancy'}), '(environment, tFlow=t_flow, thermal=True,\n method=2, supplyTemperature=t_back, occupancy=occupancy_object1.occupancy)\n', (8574, 8694), True, 'import pycity_base.classes.demand.DomesticHotWater as DomesticHotWater\n'), ((9429, 9453), 'numpy.sum', 'np.sum', (['dhw_energy_curve'], {}), '(dhw_energy_curve)\n', (9435, 9453), True, 'import numpy as np\n'), ((10102, 10151), 'pycity_calc.toolbox.dimensioning.dim_functions.get_max_p_of_power_curve', 'dimfunc.get_max_p_of_power_curve', (['dhw_power_curve'], {}), '(dhw_power_curve)\n', (10134, 10151), True, 'import pycity_calc.toolbox.dimensioning.dim_functions as dimfunc\n'), ((10322, 10342), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(2)', '(1)', '(1)'], {}), '(2, 1, 1)\n', (10333, 10342), True, 'import matplotlib.pyplot as plt\n'), ((10453, 10486), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Heat demand in Watt"""'], {}), "('Heat demand in Watt')\n", (10463, 10486), True, 'import matplotlib.pyplot as plt\n'), ((10491, 10510), 'matplotlib.pyplot.xlim', 'plt.xlim', (['(0, 8760)'], {}), '((0, 8760))\n', (10499, 10510), True, 'import matplotlib.pyplot as plt\n'), ((10536, 10586), 'pycity_base.functions.changeResolution.changeResolution', 'chres.changeResolution', (['occ_profile', '(600)', 'timestep'], {}), '(occ_profile, 600, timestep)\n', (10558, 10586), True, 'import pycity_base.functions.changeResolution as chres\n'), ((10592, 10624), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(2)', '(1)', '(2)'], {'sharex': 'ax1'}), '(2, 1, 2, sharex=ax1)\n', (10603, 10624), True, 'import matplotlib.pyplot as plt\n'), ((10726, 10756), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Active occupants"""'], {}), "('Active occupants')\n", (10736, 10756), True, 'import matplotlib.pyplot as plt\n'), ((10885, 10895), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (10893, 10895), True, 'import matplotlib.pyplot as plt\n'), ((11036, 11189), 'pycity_base.classes.demand.DomesticHotWater.DomesticHotWater', 'DomesticHotWater.DomesticHotWater', (['environment'], {'tFlow': 't_flow', 'thermal': '(True)', 'method': '(2)', 'supplyTemperature': 't_back', 'occupancy': 'occupancy_object3.occupancy'}), '(environment, tFlow=t_flow, thermal=True,\n method=2, supplyTemperature=t_back, occupancy=occupancy_object3.occupancy)\n', (11069, 11189), True, 'import pycity_base.classes.demand.DomesticHotWater as DomesticHotWater\n'), ((11924, 11948), 'numpy.sum', 'np.sum', (['dhw_energy_curve'], {}), '(dhw_energy_curve)\n', (11930, 11948), True, 'import numpy as np\n'), ((12597, 12646), 'pycity_calc.toolbox.dimensioning.dim_functions.get_max_p_of_power_curve', 'dimfunc.get_max_p_of_power_curve', (['dhw_power_curve'], {}), '(dhw_power_curve)\n', (12629, 12646), True, 'import pycity_calc.toolbox.dimensioning.dim_functions as dimfunc\n'), ((12817, 12837), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(2)', '(1)', '(1)'], {}), '(2, 1, 1)\n', (12828, 12837), True, 'import matplotlib.pyplot as plt\n'), ((12948, 12981), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Heat demand in Watt"""'], {}), "('Heat demand in Watt')\n", (12958, 12981), True, 'import matplotlib.pyplot as plt\n'), ((12986, 13005), 'matplotlib.pyplot.xlim', 'plt.xlim', (['(0, 8760)'], {}), '((0, 8760))\n', (12994, 13005), True, 'import matplotlib.pyplot as plt\n'), ((13031, 13081), 'pycity_base.functions.changeResolution.changeResolution', 'chres.changeResolution', (['occ_profile', '(600)', 'timestep'], {}), '(occ_profile, 600, timestep)\n', (13053, 13081), True, 'import pycity_base.functions.changeResolution as chres\n'), ((13087, 13119), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(2)', '(1)', '(2)'], {'sharex': 'ax1'}), '(2, 1, 2, sharex=ax1)\n', (13098, 13119), True, 'import matplotlib.pyplot as plt\n'), ((13221, 13251), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Active occupants"""'], {}), "('Active occupants')\n", (13231, 13251), True, 'import matplotlib.pyplot as plt\n'), ((13380, 13390), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (13388, 13390), True, 'import matplotlib.pyplot as plt\n'), ((13531, 13684), 'pycity_base.classes.demand.DomesticHotWater.DomesticHotWater', 'DomesticHotWater.DomesticHotWater', (['environment'], {'tFlow': 't_flow', 'thermal': '(True)', 'method': '(2)', 'supplyTemperature': 't_back', 'occupancy': 'occupancy_object5.occupancy'}), '(environment, tFlow=t_flow, thermal=True,\n method=2, supplyTemperature=t_back, occupancy=occupancy_object5.occupancy)\n', (13564, 13684), True, 'import pycity_base.classes.demand.DomesticHotWater as DomesticHotWater\n'), ((14419, 14443), 'numpy.sum', 'np.sum', (['dhw_energy_curve'], {}), '(dhw_energy_curve)\n', (14425, 14443), True, 'import numpy as np\n'), ((15092, 15141), 'pycity_calc.toolbox.dimensioning.dim_functions.get_max_p_of_power_curve', 'dimfunc.get_max_p_of_power_curve', (['dhw_power_curve'], {}), '(dhw_power_curve)\n', (15124, 15141), True, 'import pycity_calc.toolbox.dimensioning.dim_functions as dimfunc\n'), ((15312, 15332), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(2)', '(1)', '(1)'], {}), '(2, 1, 1)\n', (15323, 15332), True, 'import matplotlib.pyplot as plt\n'), ((15443, 15476), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Heat demand in Watt"""'], {}), "('Heat demand in Watt')\n", (15453, 15476), True, 'import matplotlib.pyplot as plt\n'), ((15481, 15500), 'matplotlib.pyplot.xlim', 'plt.xlim', (['(0, 8760)'], {}), '((0, 8760))\n', (15489, 15500), True, 'import matplotlib.pyplot as plt\n'), ((15526, 15576), 'pycity_base.functions.changeResolution.changeResolution', 'chres.changeResolution', (['occ_profile', '(600)', 'timestep'], {}), '(occ_profile, 600, timestep)\n', (15548, 15576), True, 'import pycity_base.functions.changeResolution as chres\n'), ((15582, 15614), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(2)', '(1)', '(2)'], {'sharex': 'ax1'}), '(2, 1, 2, sharex=ax1)\n', (15593, 15614), True, 'import matplotlib.pyplot as plt\n'), ((15716, 15746), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Active occupants"""'], {}), "('Active occupants')\n", (15726, 15746), True, 'import matplotlib.pyplot as plt\n'), ((15875, 15885), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (15883, 15885), True, 'import matplotlib.pyplot as plt\n'), ((4060, 4097), 'numpy.arange', 'np.arange', (['(365 * 24 * 3600 / timestep)'], {}), '(365 * 24 * 3600 / timestep)\n', (4069, 4097), True, 'import numpy as np\n'), ((5963, 6000), 'numpy.arange', 'np.arange', (['(365 * 24 * 3600 / timestep)'], {}), '(365 * 24 * 3600 / timestep)\n', (5972, 6000), True, 'import numpy as np\n'), ((7865, 7902), 'numpy.arange', 'np.arange', (['(365 * 24 * 3600 / timestep)'], {}), '(365 * 24 * 3600 / timestep)\n', (7874, 7902), True, 'import numpy as np\n'), ((9730, 9763), 'numpy.sum', 'np.sum', (['water_volume_per_timestep'], {}), '(water_volume_per_timestep)\n', (9736, 9763), True, 'import numpy as np\n'), ((10356, 10393), 'numpy.arange', 'np.arange', (['(365 * 24 * 3600 / timestep)'], {}), '(365 * 24 * 3600 / timestep)\n', (10365, 10393), True, 'import numpy as np\n'), ((10638, 10675), 'numpy.arange', 'np.arange', (['(365 * 24 * 3600 / timestep)'], {}), '(365 * 24 * 3600 / timestep)\n', (10647, 10675), True, 'import numpy as np\n'), ((12225, 12258), 'numpy.sum', 'np.sum', (['water_volume_per_timestep'], {}), '(water_volume_per_timestep)\n', (12231, 12258), True, 'import numpy as np\n'), ((12851, 12888), 'numpy.arange', 'np.arange', (['(365 * 24 * 3600 / timestep)'], {}), '(365 * 24 * 3600 / timestep)\n', (12860, 12888), True, 'import numpy as np\n'), ((13133, 13170), 'numpy.arange', 'np.arange', (['(365 * 24 * 3600 / timestep)'], {}), '(365 * 24 * 3600 / timestep)\n', (13142, 13170), True, 'import numpy as np\n'), ((14720, 14753), 'numpy.sum', 'np.sum', (['water_volume_per_timestep'], {}), '(water_volume_per_timestep)\n', (14726, 14753), True, 'import numpy as np\n'), ((15346, 15383), 'numpy.arange', 'np.arange', (['(365 * 24 * 3600 / timestep)'], {}), '(365 * 24 * 3600 / timestep)\n', (15355, 15383), True, 'import numpy as np\n'), ((15628, 15665), 'numpy.arange', 'np.arange', (['(365 * 24 * 3600 / timestep)'], {}), '(365 * 24 * 3600 / timestep)\n', (15637, 15665), True, 'import numpy as np\n')] |
import numpy as np
import os
import matplotlib.pyplot as plt
from sklearn.manifold import TSNE
checkpoint_dir='' # folder where checkpoints and qn/passage tokens were saved
embs_dir='' # folder where embeddings are stored
# TSNE
plt.rcParams.update({'font.size': 15})
ds=[]
for i in range(12) :
d=np.load(embs_dir+'/emb_enclayer_'+str(i)+'.npy',allow_pickle=True,encoding='latin1').item()
ds.append(d)
ids=list(ds[0].keys())
tokens=np.load(checkpoint_dir+'/qn_and_doc_tokens.npy',encoding='latin1',allow_pickle=True).item()
#colors=['black','red','blue','green','magenta','cyan','yellow','gray','indigo','darkolivegreen','crimson','slateblue']
qns=range(30,40)
# plotting only questions 30-39 for now
for i in qns :
if i%1==0 :
print(i)
words=tokens[ids[i]]
print(' '.join(words))
print('\n')
seq_len=len(words)
for j in range(12) :
start_ind=ds[j][ids[i]]['start_ind']
end_ind=ds[j][ids[i]]['end_ind']
words=ds[j][ids[i]]['words']
#print(start_ind,end_ind,' '.join(words))
sep1=words.index('[SEP]')
try :
full1=words[(end_ind+1):].index('.')+end_ind
except :
full1=end_ind+5
try :
tmp=words[:start_ind]
full2=len(tmp)-1-tmp[::-1].index('.')
except :
full2=start_ind-4
#print(full2,full1,sep1)
#os.sys.exit()
tsne_rep=TSNE(n_components=2,perplexity=40,random_state=0).fit_transform(ds[j][ids[i]]['emb'])
assert tsne_rep.shape[0]==seq_len
tsne_x=tsne_rep[:,0]
tsne_y=tsne_rep[:,1]
plt.figure(figsize=(8,8))
plt.title('t-SNE plot for Question '+str(qns[i])+', for Layer '+str(j),fontsize=22)
ll=[0,0,0,0]
lines=[]
labels=[]
for k in range(len(tsne_x)) :
fontcolor='k'
fontsize=16
label=''
if k in range(start_ind,end_ind+1) : # ans span
color='r'
ms=600
marker='o'
if ll[0]==0 :
ll[0]=k
label='answer span'
elif words[k]=='[CLS]' or words[k]=='[SEP]' :
color='k'
ms=250
marker='s'
if ll[1]==0 :
ll[1]=k
label='[CLS]/[SEP]'
elif k in range(1,sep1) : # qn words
color='green'
ms=250
marker='v'
if ll[2]==0 :
ll[2]=k
label='query words'
#elif (k not in range(1,sep1)) and (words[k] in words[1:sep1]) :
# color='slategray'
# ms=200
elif (k in range(full2,start_ind)) or (k in range(end_ind+1,full1)) : # contextual
color='fuchsia'
ms=250
marker='X'
if ll[3]==0 :
ll[3]=k
label='contextual words'
else :
color='lightsteelblue'
ms=50
fontcolor='lightgray'
fontsize=6
marker='.'
sc=plt.scatter(tsne_x[k],tsne_y[k],c=color,cmap=plt.cm.get_cmap("jet",10),s=ms,marker=marker,label=label)
#pp,qq=sc.legend_elements()
lines.append(sc)#pp)
labels.append(label)#qq)
plt.annotate(words[k],xy=(tsne_x[k],tsne_y[k]),xytext=(5,2),
textcoords='offset points',ha='right',va='bottom',fontsize=fontsize,color=fontcolor)
#plt.colorbar(ticks=range(10))
final_lines=[]
final_labels=[]#'answer span','[CLS]/[SEP]','query words','contextual words']
for k in range(4) :
final_lines.append(lines[ll[k]])
final_labels.append(labels[ll[k]])
#final_labels.append(final_lines[k].get_label())
print(final_lines)
print(final_labels)
plt.legend(handles=final_lines,labels=final_labels,fontsize=16,loc='best')
plt.savefig('tsne_plots/tsne_perplexity_40/tsne_qn_'+str(qns[i])+'_layer_'+str(j))
plt.tight_layout()
plt.close()
print('TSNE DONE!')
| [
"numpy.load",
"matplotlib.pyplot.annotate",
"sklearn.manifold.TSNE",
"matplotlib.pyplot.close",
"matplotlib.pyplot.legend",
"matplotlib.pyplot.figure",
"matplotlib.pyplot.rcParams.update",
"matplotlib.pyplot.tight_layout",
"matplotlib.pyplot.cm.get_cmap"
] | [((231, 269), 'matplotlib.pyplot.rcParams.update', 'plt.rcParams.update', (["{'font.size': 15}"], {}), "({'font.size': 15})\n", (250, 269), True, 'import matplotlib.pyplot as plt\n'), ((437, 529), 'numpy.load', 'np.load', (["(checkpoint_dir + '/qn_and_doc_tokens.npy')"], {'encoding': '"""latin1"""', 'allow_pickle': '(True)'}), "(checkpoint_dir + '/qn_and_doc_tokens.npy', encoding='latin1',\n allow_pickle=True)\n", (444, 529), True, 'import numpy as np\n'), ((1451, 1477), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(8, 8)'}), '(figsize=(8, 8))\n', (1461, 1477), True, 'import matplotlib.pyplot as plt\n'), ((3186, 3263), 'matplotlib.pyplot.legend', 'plt.legend', ([], {'handles': 'final_lines', 'labels': 'final_labels', 'fontsize': '(16)', 'loc': '"""best"""'}), "(handles=final_lines, labels=final_labels, fontsize=16, loc='best')\n", (3196, 3263), True, 'import matplotlib.pyplot as plt\n'), ((3352, 3370), 'matplotlib.pyplot.tight_layout', 'plt.tight_layout', ([], {}), '()\n', (3368, 3370), True, 'import matplotlib.pyplot as plt\n'), ((3373, 3384), 'matplotlib.pyplot.close', 'plt.close', ([], {}), '()\n', (3382, 3384), True, 'import matplotlib.pyplot as plt\n'), ((2713, 2876), 'matplotlib.pyplot.annotate', 'plt.annotate', (['words[k]'], {'xy': '(tsne_x[k], tsne_y[k])', 'xytext': '(5, 2)', 'textcoords': '"""offset points"""', 'ha': '"""right"""', 'va': '"""bottom"""', 'fontsize': 'fontsize', 'color': 'fontcolor'}), "(words[k], xy=(tsne_x[k], tsne_y[k]), xytext=(5, 2), textcoords\n ='offset points', ha='right', va='bottom', fontsize=fontsize, color=\n fontcolor)\n", (2725, 2876), True, 'import matplotlib.pyplot as plt\n'), ((1280, 1331), 'sklearn.manifold.TSNE', 'TSNE', ([], {'n_components': '(2)', 'perplexity': '(40)', 'random_state': '(0)'}), '(n_components=2, perplexity=40, random_state=0)\n', (1284, 1331), False, 'from sklearn.manifold import TSNE\n'), ((2569, 2595), 'matplotlib.pyplot.cm.get_cmap', 'plt.cm.get_cmap', (['"""jet"""', '(10)'], {}), "('jet', 10)\n", (2584, 2595), True, 'import matplotlib.pyplot as plt\n')] |
import numpy as np
import torch
from torch.utils.data import DataLoader
import pytorch_lightning as pl
from transformers import (
AdamW,
get_linear_schedule_with_warmup,
)
#emb_sz_rule from fastai: https://github.com/fastai/fastai/blob/master/fastai/tabular/data.py
def emb_sz_rule(n_cat:int)->int: return min(600, round(1.6 * n_cat**0.56))
class PointwiseFinetuner(pl.LightningModule):
def __init__(self, hparams,train_dataset,valid_dataset,test_dataset):
super(PointwiseFinetuner, self).__init__()
self.hparams = hparams
self.train_dataset = train_dataset
self.valid_dataset = valid_dataset
self.test_dataset = test_dataset
#construct layers
self.n_cat = sum([emb_sz_rule(i) for i in self.hparams.cat_dims])
self.n_num = self.hparams.n_num
self.emb = torch.nn.ModuleList([torch.nn.Embedding(i, emb_sz_rule(i)) for i in self.hparams.cat_dims])
self.emb_droupout = torch.nn.Dropout(self.hparams.emb_drop)
self.head = torch.nn.Sequential(
torch.nn.Linear(self.n_cat + self.n_num, self.hparams.num_hidden),
torch.nn.Dropout(p=self.hparams.drop),
torch.nn.Linear(self.hparams.num_hidden, 1),
# torch.nn.Sigmoid()
)
#loss
self.loss_fn = torch.nn.MSELoss()
def forward(self,inp):
cat_x = inp['cat_feature']
cat_x = [e(cat_x[:,i]) for i,e in enumerate(self.emb)]
cat_x = torch.cat(cat_x, 1)
cat_x = self.emb_droupout(cat_x)
x = torch.cat([cat_x,inp['num_feature']],1)
x = self.head(x)
# x = (self.hparams.y_range[1]-self.hparams.y_range[0]) * x + self.hparams.y_range[0]
return x
def _step(self, batch):
preds = self.forward(batch)
loss = self.loss_fn(preds, batch['label'])
return loss, preds
def training_step(self, batch, batch_nb):
loss, _ = self._step(batch)
tensorboard_logs = {'train_loss': loss.cpu()}
return {'loss': loss.cpu(), 'log': tensorboard_logs}
def validation_step(self, batch, batch_nb):
loss, preds = self._step(batch)
tensorboard_logs = {'train_loss': loss.cpu()}
return {'loss': loss.cpu(), 'log': tensorboard_logs}
def validation_epoch_end(self, outputs):
avg_val_loss = np.stack([x['loss'] for x in outputs]).mean()
tensorboard_logs = {'val_loss': avg_val_loss,}
return {'val_loss': avg_val_loss,
'log': tensorboard_logs,
'progress_bar': tensorboard_logs}
def test_step(self, batch, batch_nb):
loss, preds = self._step(batch)
tensorboard_logs = {'train_loss': loss.cpu()}
return {'loss': loss.cpu(), 'log': tensorboard_logs}
def test_epoch_end(self, outputs):
avg_test_loss = np.stack([x['loss'] for x in outputs]).mean()
tensorboard_logs = {'test_loss': avg_test_loss,}
return {'test_loss': avg_test_loss,
'log': tensorboard_logs,
'progress_bar': tensorboard_logs}
def configure_optimizers(self):
no_decay = ["bias"]
optimizer_grouped_parameters = [
{
"params": [
p
for n, p in self.named_parameters()
if not any(nd in n for nd in no_decay)
],
"weight_decay": self.hparams.weight_decay,
},
{
"params": [
p
for n, p in self.named_parameters()
if any(nd in n for nd in no_decay)
],
"weight_decay": 0.0,
},
]
optimizer = AdamW(
optimizer_grouped_parameters,
lr=self.hparams.learning_rate,
eps=self.hparams.adam_epsilon,
)
self.opt = optimizer
return [optimizer]
def optimizer_step(
self, epoch, batch_idx, optimizer, optimizer_idx, second_order_closure=None,
on_tpu=False, using_native_amp=False, using_lbfgs=False
):
optimizer.step()
optimizer.zero_grad()
self.lr_scheduler.step()
def train_dataloader(self):
dataloader = DataLoader(
self.train_dataset,
batch_size=self.hparams.per_device_train_batch_size,
drop_last=True,
shuffle=True,
num_workers=0,
)
#calculate total timesteps
t_total = (
(
len(dataloader.dataset)
// (self.hparams.per_device_train_batch_size * max(1, self.hparams.n_gpu))
)
// self.hparams.gradient_accumulation_steps
* float(self.hparams.num_train_epochs)
)
#create scheduler
scheduler = get_linear_schedule_with_warmup(
self.opt,
num_warmup_steps=self.hparams.warmup_steps,
num_training_steps=t_total,
)
self.lr_scheduler = scheduler
return dataloader
def val_dataloader(self):
return DataLoader(
self.valid_dataset, batch_size=self.hparams.per_device_eval_batch_size, num_workers=0
)
def test_dataloader(self):
return DataLoader(
self.test_dataset, batch_size=self.hparams.per_device_eval_batch_size, num_workers=0
)
class PairwiseFinetuner(pl.LightningModule):
def __init__(self, hparams,train_dataset,valid_dataset,test_dataset):
super(PairwiseFinetuner, self).__init__()
self.hparams = hparams
self.train_dataset = train_dataset
self.valid_dataset = valid_dataset
self.test_dataset = test_dataset
#construct layers
self.n_cat = sum([emb_sz_rule(i) for i in self.hparams.cat_dims])
self.n_num = self.hparams.n_num
self.emb = torch.nn.ModuleList([torch.nn.Embedding(i, emb_sz_rule(i)) for i in self.hparams.cat_dims])
self.emb_droupout = torch.nn.Dropout(self.hparams.emb_drop)
self.head = torch.nn.Sequential(
torch.nn.Linear(self.n_cat + self.n_num, self.hparams.num_hidden),
torch.nn.Dropout(p=self.hparams.drop),
torch.nn.Linear(self.hparams.num_hidden, 1),
# torch.nn.Sigmoid()
)
#loss
# self.loss_fn = torch.nn.BCELoss()
self.loss_fn = torch.nn.BCEWithLogitsLoss()
def predict(self,inp):
cat_i = inp['cat_feature_i']
cat_i = [e(cat_i[:,idx]) for idx,e in enumerate(self.emb)]
cat_i = torch.cat(cat_i, 1)
cat_i = self.emb_droupout(cat_i)
x_i = torch.cat([cat_i,inp['num_feature_i']],1)
x_i = self.head(x_i)
return x_i
def forward(self,inp):
#i
cat_i = inp['cat_feature_i']
cat_i = [e(cat_i[:,idx]) for idx,e in enumerate(self.emb)]
cat_i = torch.cat(cat_i, 1)
cat_i = self.emb_droupout(cat_i)
x_i = torch.cat([cat_i,inp['num_feature_i']],1)
x_i = self.head(x_i)
#j
cat_j = inp['cat_feature_j']
cat_j = [e(cat_j[:,idx]) for idx,e in enumerate(self.emb)]
cat_j = torch.cat(cat_j, 1)
cat_j = self.emb_droupout(cat_j)
x_j = torch.cat([cat_j,inp['num_feature_j']],1)
x_j = self.head(x_j)
return x_i-x_j
def _step(self, batch):
preds = self.forward(batch)
loss = self.loss_fn(preds, batch['label'])
return loss, preds
def training_step(self, batch, batch_nb):
loss, _ = self._step(batch)
tensorboard_logs = {'train_loss': loss.cpu()}
return {'loss': loss.cpu(), 'log': tensorboard_logs}
def validation_step(self, batch, batch_nb):
loss, preds = self._step(batch)
tensorboard_logs = {'train_loss': loss.cpu()}
return {'loss': loss.cpu(), 'log': tensorboard_logs}
def validation_epoch_end(self, outputs):
avg_val_loss = np.stack([x['loss'] for x in outputs]).mean()
tensorboard_logs = {'val_loss': avg_val_loss,}
return {'val_loss': avg_val_loss,
'log': tensorboard_logs,
'progress_bar': tensorboard_logs}
def test_step(self, batch, batch_nb):
loss, preds = self._step(batch)
tensorboard_logs = {'train_loss': loss.cpu()}
return {'loss': loss.cpu(), 'log': tensorboard_logs}
def test_epoch_end(self, outputs):
avg_test_loss = np.stack([x['loss'] for x in outputs]).mean()
tensorboard_logs = {'test_loss': avg_test_loss,}
return {'test_loss': avg_test_loss,
'log': tensorboard_logs,
'progress_bar': tensorboard_logs}
def configure_optimizers(self):
no_decay = ["bias"]
optimizer_grouped_parameters = [
{
"params": [
p
for n, p in self.named_parameters()
if not any(nd in n for nd in no_decay)
],
"weight_decay": self.hparams.weight_decay,
},
{
"params": [
p
for n, p in self.named_parameters()
if any(nd in n for nd in no_decay)
],
"weight_decay": 0.0,
},
]
optimizer = AdamW(
optimizer_grouped_parameters,
lr=self.hparams.learning_rate,
eps=self.hparams.adam_epsilon,
)
self.opt = optimizer
return [optimizer]
def optimizer_step(
self, epoch, batch_idx, optimizer, optimizer_idx, second_order_closure=None,
on_tpu=False, using_native_amp=False, using_lbfgs=False
):
optimizer.step()
optimizer.zero_grad()
self.lr_scheduler.step()
def train_dataloader(self):
dataloader = DataLoader(
self.train_dataset,
batch_size=self.hparams.per_device_train_batch_size,
drop_last=True,
shuffle=True,
num_workers=0,
)
#calculate total timesteps
t_total = (
(
len(dataloader.dataset)
// (self.hparams.per_device_train_batch_size * max(1, self.hparams.n_gpu))
)
// self.hparams.gradient_accumulation_steps
* float(self.hparams.num_train_epochs)
)
#create scheduler
scheduler = get_linear_schedule_with_warmup(
self.opt,
num_warmup_steps=self.hparams.warmup_steps,
num_training_steps=t_total,
)
self.lr_scheduler = scheduler
return dataloader
def val_dataloader(self):
return DataLoader(
self.valid_dataset, batch_size=self.hparams.per_device_eval_batch_size, num_workers=0
)
def test_dataloader(self):
return DataLoader(
self.test_dataset, batch_size=self.hparams.per_device_eval_batch_size, num_workers=0
) | [
"torch.nn.Dropout",
"numpy.stack",
"torch.nn.MSELoss",
"torch.nn.BCEWithLogitsLoss",
"torch.utils.data.DataLoader",
"torch.cat",
"transformers.get_linear_schedule_with_warmup",
"transformers.AdamW",
"torch.nn.Linear"
] | [((978, 1017), 'torch.nn.Dropout', 'torch.nn.Dropout', (['self.hparams.emb_drop'], {}), '(self.hparams.emb_drop)\n', (994, 1017), False, 'import torch\n'), ((1335, 1353), 'torch.nn.MSELoss', 'torch.nn.MSELoss', ([], {}), '()\n', (1351, 1353), False, 'import torch\n'), ((1496, 1515), 'torch.cat', 'torch.cat', (['cat_x', '(1)'], {}), '(cat_x, 1)\n', (1505, 1515), False, 'import torch\n'), ((1569, 1610), 'torch.cat', 'torch.cat', (["[cat_x, inp['num_feature']]", '(1)'], {}), "([cat_x, inp['num_feature']], 1)\n", (1578, 1610), False, 'import torch\n'), ((3759, 3861), 'transformers.AdamW', 'AdamW', (['optimizer_grouped_parameters'], {'lr': 'self.hparams.learning_rate', 'eps': 'self.hparams.adam_epsilon'}), '(optimizer_grouped_parameters, lr=self.hparams.learning_rate, eps=self\n .hparams.adam_epsilon)\n', (3764, 3861), False, 'from transformers import AdamW, get_linear_schedule_with_warmup\n'), ((4283, 4416), 'torch.utils.data.DataLoader', 'DataLoader', (['self.train_dataset'], {'batch_size': 'self.hparams.per_device_train_batch_size', 'drop_last': '(True)', 'shuffle': '(True)', 'num_workers': '(0)'}), '(self.train_dataset, batch_size=self.hparams.\n per_device_train_batch_size, drop_last=True, shuffle=True, num_workers=0)\n', (4293, 4416), False, 'from torch.utils.data import DataLoader\n'), ((4869, 4987), 'transformers.get_linear_schedule_with_warmup', 'get_linear_schedule_with_warmup', (['self.opt'], {'num_warmup_steps': 'self.hparams.warmup_steps', 'num_training_steps': 't_total'}), '(self.opt, num_warmup_steps=self.hparams.\n warmup_steps, num_training_steps=t_total)\n', (4900, 4987), False, 'from transformers import AdamW, get_linear_schedule_with_warmup\n'), ((5140, 5242), 'torch.utils.data.DataLoader', 'DataLoader', (['self.valid_dataset'], {'batch_size': 'self.hparams.per_device_eval_batch_size', 'num_workers': '(0)'}), '(self.valid_dataset, batch_size=self.hparams.\n per_device_eval_batch_size, num_workers=0)\n', (5150, 5242), False, 'from torch.utils.data import DataLoader\n'), ((5307, 5408), 'torch.utils.data.DataLoader', 'DataLoader', (['self.test_dataset'], {'batch_size': 'self.hparams.per_device_eval_batch_size', 'num_workers': '(0)'}), '(self.test_dataset, batch_size=self.hparams.\n per_device_eval_batch_size, num_workers=0)\n', (5317, 5408), False, 'from torch.utils.data import DataLoader\n'), ((6055, 6094), 'torch.nn.Dropout', 'torch.nn.Dropout', (['self.hparams.emb_drop'], {}), '(self.hparams.emb_drop)\n', (6071, 6094), False, 'import torch\n'), ((6456, 6484), 'torch.nn.BCEWithLogitsLoss', 'torch.nn.BCEWithLogitsLoss', ([], {}), '()\n', (6482, 6484), False, 'import torch\n'), ((6634, 6653), 'torch.cat', 'torch.cat', (['cat_i', '(1)'], {}), '(cat_i, 1)\n', (6643, 6653), False, 'import torch\n'), ((6709, 6752), 'torch.cat', 'torch.cat', (["[cat_i, inp['num_feature_i']]", '(1)'], {}), "([cat_i, inp['num_feature_i']], 1)\n", (6718, 6752), False, 'import torch\n'), ((6958, 6977), 'torch.cat', 'torch.cat', (['cat_i', '(1)'], {}), '(cat_i, 1)\n', (6967, 6977), False, 'import torch\n'), ((7033, 7076), 'torch.cat', 'torch.cat', (["[cat_i, inp['num_feature_i']]", '(1)'], {}), "([cat_i, inp['num_feature_i']], 1)\n", (7042, 7076), False, 'import torch\n'), ((7236, 7255), 'torch.cat', 'torch.cat', (['cat_j', '(1)'], {}), '(cat_j, 1)\n', (7245, 7255), False, 'import torch\n'), ((7311, 7354), 'torch.cat', 'torch.cat', (["[cat_j, inp['num_feature_j']]", '(1)'], {}), "([cat_j, inp['num_feature_j']], 1)\n", (7320, 7354), False, 'import torch\n'), ((9420, 9522), 'transformers.AdamW', 'AdamW', (['optimizer_grouped_parameters'], {'lr': 'self.hparams.learning_rate', 'eps': 'self.hparams.adam_epsilon'}), '(optimizer_grouped_parameters, lr=self.hparams.learning_rate, eps=self\n .hparams.adam_epsilon)\n', (9425, 9522), False, 'from transformers import AdamW, get_linear_schedule_with_warmup\n'), ((9944, 10077), 'torch.utils.data.DataLoader', 'DataLoader', (['self.train_dataset'], {'batch_size': 'self.hparams.per_device_train_batch_size', 'drop_last': '(True)', 'shuffle': '(True)', 'num_workers': '(0)'}), '(self.train_dataset, batch_size=self.hparams.\n per_device_train_batch_size, drop_last=True, shuffle=True, num_workers=0)\n', (9954, 10077), False, 'from torch.utils.data import DataLoader\n'), ((10530, 10648), 'transformers.get_linear_schedule_with_warmup', 'get_linear_schedule_with_warmup', (['self.opt'], {'num_warmup_steps': 'self.hparams.warmup_steps', 'num_training_steps': 't_total'}), '(self.opt, num_warmup_steps=self.hparams.\n warmup_steps, num_training_steps=t_total)\n', (10561, 10648), False, 'from transformers import AdamW, get_linear_schedule_with_warmup\n'), ((10801, 10903), 'torch.utils.data.DataLoader', 'DataLoader', (['self.valid_dataset'], {'batch_size': 'self.hparams.per_device_eval_batch_size', 'num_workers': '(0)'}), '(self.valid_dataset, batch_size=self.hparams.\n per_device_eval_batch_size, num_workers=0)\n', (10811, 10903), False, 'from torch.utils.data import DataLoader\n'), ((10968, 11069), 'torch.utils.data.DataLoader', 'DataLoader', (['self.test_dataset'], {'batch_size': 'self.hparams.per_device_eval_batch_size', 'num_workers': '(0)'}), '(self.test_dataset, batch_size=self.hparams.\n per_device_eval_batch_size, num_workers=0)\n', (10978, 11069), False, 'from torch.utils.data import DataLoader\n'), ((1071, 1136), 'torch.nn.Linear', 'torch.nn.Linear', (['(self.n_cat + self.n_num)', 'self.hparams.num_hidden'], {}), '(self.n_cat + self.n_num, self.hparams.num_hidden)\n', (1086, 1136), False, 'import torch\n'), ((1150, 1187), 'torch.nn.Dropout', 'torch.nn.Dropout', ([], {'p': 'self.hparams.drop'}), '(p=self.hparams.drop)\n', (1166, 1187), False, 'import torch\n'), ((1201, 1244), 'torch.nn.Linear', 'torch.nn.Linear', (['self.hparams.num_hidden', '(1)'], {}), '(self.hparams.num_hidden, 1)\n', (1216, 1244), False, 'import torch\n'), ((6148, 6213), 'torch.nn.Linear', 'torch.nn.Linear', (['(self.n_cat + self.n_num)', 'self.hparams.num_hidden'], {}), '(self.n_cat + self.n_num, self.hparams.num_hidden)\n', (6163, 6213), False, 'import torch\n'), ((6227, 6264), 'torch.nn.Dropout', 'torch.nn.Dropout', ([], {'p': 'self.hparams.drop'}), '(p=self.hparams.drop)\n', (6243, 6264), False, 'import torch\n'), ((6278, 6321), 'torch.nn.Linear', 'torch.nn.Linear', (['self.hparams.num_hidden', '(1)'], {}), '(self.hparams.num_hidden, 1)\n', (6293, 6321), False, 'import torch\n'), ((2367, 2405), 'numpy.stack', 'np.stack', (["[x['loss'] for x in outputs]"], {}), "([x['loss'] for x in outputs])\n", (2375, 2405), True, 'import numpy as np\n'), ((2863, 2901), 'numpy.stack', 'np.stack', (["[x['loss'] for x in outputs]"], {}), "([x['loss'] for x in outputs])\n", (2871, 2901), True, 'import numpy as np\n'), ((8028, 8066), 'numpy.stack', 'np.stack', (["[x['loss'] for x in outputs]"], {}), "([x['loss'] for x in outputs])\n", (8036, 8066), True, 'import numpy as np\n'), ((8524, 8562), 'numpy.stack', 'np.stack', (["[x['loss'] for x in outputs]"], {}), "([x['loss'] for x in outputs])\n", (8532, 8562), True, 'import numpy as np\n')] |
# import the necessary packages
from keras.preprocessing.image import img_to_array
from keras.models import load_model
import numpy as np
import imutils
import pickle
import cv2
import os
import matplotlib.pyplot as plt
image_path = os.path.join("..", "sample.png")
model_path = os.path.join("..", "models" , "plant_disease.model")
binarizer_path = os.path.join("..", "models" , "plant_disease.pickle")
# load the image
image = cv2.imread(image_path)
output = image.copy()
# pre-process the image for classification
image = cv2.resize(image, (80, 80))
image = image.astype("float") / 255.0
image = img_to_array(image)
image = np.expand_dims(image, axis=0)
# load the trained convolutional neural network and the label
# binarizer
print("[INFO] loading network...")
model = load_model(model_path)
lb = pickle.loads(open(binarizer_path, "rb").read())
print(lb.classes_)
# classify the input image
print("[INFO] classifying image...")
proba = model.predict(image)[0]
idx = np.argmax(proba)
label = lb.classes_[idx]
cv2.putText(output, label, (10, 25), cv2.FONT_HERSHEY_SIMPLEX,
0.7, (0, 255, 0), 2)
cv2.putText(output, str(np.max(proba)), (10, 55), cv2.FONT_HERSHEY_SIMPLEX,
0.7, (0, 0, 255), 2)
# # show the output image
cv2.imshow("Output", output)
cv2.waitKey(0)
cv2.destroyAllWindows() | [
"keras.models.load_model",
"cv2.putText",
"numpy.argmax",
"cv2.waitKey",
"cv2.destroyAllWindows",
"numpy.expand_dims",
"cv2.imread",
"keras.preprocessing.image.img_to_array",
"numpy.max",
"cv2.imshow",
"os.path.join",
"cv2.resize"
] | [((234, 266), 'os.path.join', 'os.path.join', (['""".."""', '"""sample.png"""'], {}), "('..', 'sample.png')\n", (246, 266), False, 'import os\n'), ((280, 331), 'os.path.join', 'os.path.join', (['""".."""', '"""models"""', '"""plant_disease.model"""'], {}), "('..', 'models', 'plant_disease.model')\n", (292, 331), False, 'import os\n'), ((350, 402), 'os.path.join', 'os.path.join', (['""".."""', '"""models"""', '"""plant_disease.pickle"""'], {}), "('..', 'models', 'plant_disease.pickle')\n", (362, 402), False, 'import os\n'), ((430, 452), 'cv2.imread', 'cv2.imread', (['image_path'], {}), '(image_path)\n', (440, 452), False, 'import cv2\n'), ((528, 555), 'cv2.resize', 'cv2.resize', (['image', '(80, 80)'], {}), '(image, (80, 80))\n', (538, 555), False, 'import cv2\n'), ((602, 621), 'keras.preprocessing.image.img_to_array', 'img_to_array', (['image'], {}), '(image)\n', (614, 621), False, 'from keras.preprocessing.image import img_to_array\n'), ((630, 659), 'numpy.expand_dims', 'np.expand_dims', (['image'], {'axis': '(0)'}), '(image, axis=0)\n', (644, 659), True, 'import numpy as np\n'), ((778, 800), 'keras.models.load_model', 'load_model', (['model_path'], {}), '(model_path)\n', (788, 800), False, 'from keras.models import load_model\n'), ((976, 992), 'numpy.argmax', 'np.argmax', (['proba'], {}), '(proba)\n', (985, 992), True, 'import numpy as np\n'), ((1018, 1105), 'cv2.putText', 'cv2.putText', (['output', 'label', '(10, 25)', 'cv2.FONT_HERSHEY_SIMPLEX', '(0.7)', '(0, 255, 0)', '(2)'], {}), '(output, label, (10, 25), cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0, 255,\n 0), 2)\n', (1029, 1105), False, 'import cv2\n'), ((1230, 1258), 'cv2.imshow', 'cv2.imshow', (['"""Output"""', 'output'], {}), "('Output', output)\n", (1240, 1258), False, 'import cv2\n'), ((1259, 1273), 'cv2.waitKey', 'cv2.waitKey', (['(0)'], {}), '(0)\n', (1270, 1273), False, 'import cv2\n'), ((1274, 1297), 'cv2.destroyAllWindows', 'cv2.destroyAllWindows', ([], {}), '()\n', (1295, 1297), False, 'import cv2\n'), ((1128, 1141), 'numpy.max', 'np.max', (['proba'], {}), '(proba)\n', (1134, 1141), True, 'import numpy as np\n')] |
import numpy as np
from sklearn.base import BaseEstimator
from qpsolvers import solve_qp
from scipy.integrate import trapz
from pwass.spline import MonotoneQuadraticSplineBasis
from pwass.distributions import Distribution
class DistribOnDistribReg(BaseEstimator):
def __init__(self, fit_intercept=True, nbasis=-1, spline_basis=None,
compute_spline=True, lambda_ridge=0, rho_ps=0.0,
method="ridge"):
self.fit_intercept = fit_intercept
self.nbasis = nbasis
self.spline_basis = spline_basis
self.compute_spline = compute_spline
self.lambda_ridge = lambda_ridge
self.rho_ps = rho_ps
self.method = method
def _initialize(self):
if self.spline_basis is None:
self.spline_basis = MonotoneQuadraticSplineBasis(
self.nbasis, np.linspace(0, 1, 100))
else:
self.nbasis = self.spline_basis.nbasis
self.spline_basis.eval_metric()
self.constraints_mat = np.zeros((self.nbasis - 1, self.nbasis))
for i in range(self.nbasis-1):
self.constraints_mat[i, i] = 1
self.constraints_mat[i, i+1] = -1
self.cons_rhs = np.zeros((self.nbasis-1,))
def fit(self, X, Y):
self._initialize()
self.n_samples = len(X)
self.X = X
self.Y = Y
if self.compute_spline:
for x in self.X:
x.wbasis = self.spline_basis
x.compute_spline_expansions()
for y in self.Y:
y.wbasis = self.spline_basis
y.compute_spline_expansions()
self.Xmat = self.get_spline_mat(self.X)
self.Ymat = self.get_spline_mat(self.Y)
if self.fit_intercept:
self.Xmat = np.hstack(
[np.ones(self.n_samples).reshape(-1, 1), self.Xmat])
if self.method == "ridge":
self._fit_ridge()
else:
assert self.fit_intercept == False
self._fit_ps()
def predict(self, Xnew):
if self.compute_spline:
for x in Xnew:
x.wbasis = self.spline_basis
x.compute_spline_expansions()
Xmat = self.get_spline_mat(Xnew)
Ypred = np.zeros_like(Xmat)
if self.fit_intercept:
Xmat = np.hstack(
[np.ones(Xmat.shape[0]).reshape(-1, 1), Xmat])
out = []
for i in range(Xmat.shape[0]):
if self.method == "ridge":
y_ = np.matmul(Xmat[i, :], self.beta)
else:
y_ = np.matmul(
self.beta, np.matmul(self.spline_basis.metric, X[i, :]))
Ypred[i, :] = self.project(y_)
curr = Distribution(
wbasis=self.spline_basis,
smooth_sigma=Xnew[0].smooth_sigma)
curr.init_from_quantile(
self.spline_basis.xgrid, self.spline_basis.eval_spline(
Ypred[i, :]))
curr.quantile_coeffs = Ypred[i, :]
out.append(curr)
return out
def score(self, X, ytrue, return_sd=False):
ypred = self.predict(X)
errs = np.zeros(len(ypred))
out = 0.0
for i in range(len(ypred)):
ytrue_eval = self.spline_basis.eval_spline(
ytrue[i].quantile_coeffs)
ypred_eval = self.spline_basis.eval_spline(
ypred[i].quantile_coeffs)
errs[i] = trapz((ytrue_eval - ypred_eval)**2,
self.spline_basis.xgrid)
if return_sd:
return np.mean(errs), np.std(errs)
else:
return -np.mean(errs)
def project(self, y):
out = solve_qp(
self.spline_basis.metric * 2,
-2 * np.dot(self.spline_basis.metric, y),
self.constraints_mat, self.cons_rhs)
return out
def get_spline_mat(self, distribs):
"""Stacks all the coefficient of the spline expansions by row
"""
out = np.zeros((len(distribs), self.nbasis))
for i, d in enumerate(distribs):
out[i, :] = d.quantile_coeffs
eps = np.ones(out.shape[1]) * 1e-6
for i in range(out.shape[1]):
out[:, i] += np.sum(eps[:i])
return out
def _fit_ridge(self):
XXtrans = np.matmul(self.Xmat.T, self.Xmat)
self.beta = np.linalg.solve(
XXtrans + self.lambda_ridge * np.eye(XXtrans.shape[0]),
np.matmul(self.Xmat.T, self.Ymat))
def _fit_ps(self):
self._compute_e_prime()
Chat = np.zeros((self.nbasis, self.nbasis))
Dhat = np.zeros((self.nbasis, self.nbasis))
E = self.spline_basis.metric
for k in range(self.nbasis):
ek = np.zeros(self.nbasis)
ek[k] = 1.0
inner_prods = np.matmul(self.Xmat, np.matmul(
self.spline_basis.metric, ek))
X_times_inner_prods = self.Xmat * inner_prods[:, np.newaxis]
Y_times_inner_prods = self.Ymat * inner_prods[:, np.newaxis]
for s in range(self.nbasis):
es = np.zeros(self.nbasis)
es[s] = 1.0
Chat[k, s] = np.mean(
np.matmul(X_times_inner_prods, np.matmul(E, es)))
Dhat[k, s] = np.mean(
np.matmul(Y_times_inner_prods, np.matmul(E, es)))
rho = 1e-8
Crho = np.kron(E, Chat + rho * self.Eprime)
P = np.kron(self.Eprime, self.spline_basis.metric) + \
np.kron(self.spline_basis.metric, self.Eprime)
vecbeta_hat = np.linalg.solve(Crho + rho * P, Dhat.T.reshape(-1, 1))
self.beta = vecbeta_hat.reshape(self.nbasis, self.nbasis)
def _compute_e_prime(self):
self.Eprime = np.zeros_like(self.spline_basis.metric)
for i in range(self.nbasis):
ci = np.zeros(self.nbasis)
ci[i] = 1
curr = self.spline_basis.eval_spline_der(ci)
self.Eprime[i, i] = trapz(curr * curr, self.spline_basis.xgrid)
for j in range(i):
cj = np.zeros(self.nbasis)
cj[j] = 1
other = self.spline_basis.eval_spline_der(cj)
self.Eprime[i, j] = trapz(curr * other, self.spline_basis.xgrid)
self.Eprime[j, i] = self.Eprime[i, j]
| [
"numpy.zeros_like",
"numpy.sum",
"numpy.eye",
"numpy.std",
"pwass.distributions.Distribution",
"numpy.zeros",
"numpy.ones",
"numpy.mean",
"numpy.kron",
"numpy.matmul",
"scipy.integrate.trapz",
"numpy.linspace",
"numpy.dot"
] | [((1016, 1056), 'numpy.zeros', 'np.zeros', (['(self.nbasis - 1, self.nbasis)'], {}), '((self.nbasis - 1, self.nbasis))\n', (1024, 1056), True, 'import numpy as np\n'), ((1210, 1238), 'numpy.zeros', 'np.zeros', (['(self.nbasis - 1,)'], {}), '((self.nbasis - 1,))\n', (1218, 1238), True, 'import numpy as np\n'), ((2257, 2276), 'numpy.zeros_like', 'np.zeros_like', (['Xmat'], {}), '(Xmat)\n', (2270, 2276), True, 'import numpy as np\n'), ((4346, 4379), 'numpy.matmul', 'np.matmul', (['self.Xmat.T', 'self.Xmat'], {}), '(self.Xmat.T, self.Xmat)\n', (4355, 4379), True, 'import numpy as np\n'), ((4603, 4639), 'numpy.zeros', 'np.zeros', (['(self.nbasis, self.nbasis)'], {}), '((self.nbasis, self.nbasis))\n', (4611, 4639), True, 'import numpy as np\n'), ((4655, 4691), 'numpy.zeros', 'np.zeros', (['(self.nbasis, self.nbasis)'], {}), '((self.nbasis, self.nbasis))\n', (4663, 4691), True, 'import numpy as np\n'), ((5443, 5479), 'numpy.kron', 'np.kron', (['E', '(Chat + rho * self.Eprime)'], {}), '(E, Chat + rho * self.Eprime)\n', (5450, 5479), True, 'import numpy as np\n'), ((5804, 5843), 'numpy.zeros_like', 'np.zeros_like', (['self.spline_basis.metric'], {}), '(self.spline_basis.metric)\n', (5817, 5843), True, 'import numpy as np\n'), ((2741, 2814), 'pwass.distributions.Distribution', 'Distribution', ([], {'wbasis': 'self.spline_basis', 'smooth_sigma': 'Xnew[0].smooth_sigma'}), '(wbasis=self.spline_basis, smooth_sigma=Xnew[0].smooth_sigma)\n', (2753, 2814), False, 'from pwass.distributions import Distribution\n'), ((3477, 3539), 'scipy.integrate.trapz', 'trapz', (['((ytrue_eval - ypred_eval) ** 2)', 'self.spline_basis.xgrid'], {}), '((ytrue_eval - ypred_eval) ** 2, self.spline_basis.xgrid)\n', (3482, 3539), False, 'from scipy.integrate import trapz\n'), ((4173, 4194), 'numpy.ones', 'np.ones', (['out.shape[1]'], {}), '(out.shape[1])\n', (4180, 4194), True, 'import numpy as np\n'), ((4265, 4280), 'numpy.sum', 'np.sum', (['eps[:i]'], {}), '(eps[:i])\n', (4271, 4280), True, 'import numpy as np\n'), ((4497, 4530), 'numpy.matmul', 'np.matmul', (['self.Xmat.T', 'self.Ymat'], {}), '(self.Xmat.T, self.Ymat)\n', (4506, 4530), True, 'import numpy as np\n'), ((4783, 4804), 'numpy.zeros', 'np.zeros', (['self.nbasis'], {}), '(self.nbasis)\n', (4791, 4804), True, 'import numpy as np\n'), ((5492, 5538), 'numpy.kron', 'np.kron', (['self.Eprime', 'self.spline_basis.metric'], {}), '(self.Eprime, self.spline_basis.metric)\n', (5499, 5538), True, 'import numpy as np\n'), ((5559, 5605), 'numpy.kron', 'np.kron', (['self.spline_basis.metric', 'self.Eprime'], {}), '(self.spline_basis.metric, self.Eprime)\n', (5566, 5605), True, 'import numpy as np\n'), ((5898, 5919), 'numpy.zeros', 'np.zeros', (['self.nbasis'], {}), '(self.nbasis)\n', (5906, 5919), True, 'import numpy as np\n'), ((6031, 6074), 'scipy.integrate.trapz', 'trapz', (['(curr * curr)', 'self.spline_basis.xgrid'], {}), '(curr * curr, self.spline_basis.xgrid)\n', (6036, 6074), False, 'from scipy.integrate import trapz\n'), ((854, 876), 'numpy.linspace', 'np.linspace', (['(0)', '(1)', '(100)'], {}), '(0, 1, 100)\n', (865, 876), True, 'import numpy as np\n'), ((2519, 2551), 'numpy.matmul', 'np.matmul', (['Xmat[i, :]', 'self.beta'], {}), '(Xmat[i, :], self.beta)\n', (2528, 2551), True, 'import numpy as np\n'), ((3607, 3620), 'numpy.mean', 'np.mean', (['errs'], {}), '(errs)\n', (3614, 3620), True, 'import numpy as np\n'), ((3622, 3634), 'numpy.std', 'np.std', (['errs'], {}), '(errs)\n', (3628, 3634), True, 'import numpy as np\n'), ((3669, 3682), 'numpy.mean', 'np.mean', (['errs'], {}), '(errs)\n', (3676, 3682), True, 'import numpy as np\n'), ((3794, 3829), 'numpy.dot', 'np.dot', (['self.spline_basis.metric', 'y'], {}), '(self.spline_basis.metric, y)\n', (3800, 3829), True, 'import numpy as np\n'), ((4876, 4915), 'numpy.matmul', 'np.matmul', (['self.spline_basis.metric', 'ek'], {}), '(self.spline_basis.metric, ek)\n', (4885, 4915), True, 'import numpy as np\n'), ((5142, 5163), 'numpy.zeros', 'np.zeros', (['self.nbasis'], {}), '(self.nbasis)\n', (5150, 5163), True, 'import numpy as np\n'), ((6127, 6148), 'numpy.zeros', 'np.zeros', (['self.nbasis'], {}), '(self.nbasis)\n', (6135, 6148), True, 'import numpy as np\n'), ((6273, 6317), 'scipy.integrate.trapz', 'trapz', (['(curr * other)', 'self.spline_basis.xgrid'], {}), '(curr * other, self.spline_basis.xgrid)\n', (6278, 6317), False, 'from scipy.integrate import trapz\n'), ((2633, 2677), 'numpy.matmul', 'np.matmul', (['self.spline_basis.metric', 'X[i, :]'], {}), '(self.spline_basis.metric, X[i, :])\n', (2642, 2677), True, 'import numpy as np\n'), ((4459, 4483), 'numpy.eye', 'np.eye', (['XXtrans.shape[0]'], {}), '(XXtrans.shape[0])\n', (4465, 4483), True, 'import numpy as np\n'), ((5281, 5297), 'numpy.matmul', 'np.matmul', (['E', 'es'], {}), '(E, es)\n', (5290, 5297), True, 'import numpy as np\n'), ((5389, 5405), 'numpy.matmul', 'np.matmul', (['E', 'es'], {}), '(E, es)\n', (5398, 5405), True, 'import numpy as np\n'), ((1814, 1837), 'numpy.ones', 'np.ones', (['self.n_samples'], {}), '(self.n_samples)\n', (1821, 1837), True, 'import numpy as np\n'), ((2356, 2378), 'numpy.ones', 'np.ones', (['Xmat.shape[0]'], {}), '(Xmat.shape[0])\n', (2363, 2378), True, 'import numpy as np\n')] |
def display_via_moviepy(images, title):
"""Display an animated sequence of images in the browser using moviepy."""
from moviepy.editor import ImageSequenceClip
import numpy as np
as_arrays = [np.array(image) for image in images]
return ImageSequenceClip(as_arrays, fps=24).ipython_display()
| [
"numpy.array",
"moviepy.editor.ImageSequenceClip"
] | [((209, 224), 'numpy.array', 'np.array', (['image'], {}), '(image)\n', (217, 224), True, 'import numpy as np\n'), ((257, 293), 'moviepy.editor.ImageSequenceClip', 'ImageSequenceClip', (['as_arrays'], {'fps': '(24)'}), '(as_arrays, fps=24)\n', (274, 293), False, 'from moviepy.editor import ImageSequenceClip\n')] |
import json
import os
import time
import matplotlib.pyplot as plt
import numpy as np
import tensorflow as tf
from sklearn.model_selection import train_test_split
from sklearn.utils import shuffle
from tensorflow.keras.applications.inception_v3 import *
from tensorflow.keras.layers import *
from tensorflow.keras.losses import \
SparseCategoricalCrossentropy
from tensorflow.keras.models import Model
from tensorflow.keras.optimizers import Adam
from tensorflow.keras.preprocessing.sequence import \
pad_sequences
from tensorflow.keras.preprocessing.text import Tokenizer
from tensorflow.keras.utils import get_file
AUTOTUNE = tf.data.experimental.AUTOTUNE
def load_image(image_path):
image = tf.io.read_file(image_path)
image = tf.image.decode_jpeg(image, channels=3)
image = tf.image.resize(image, (299, 299))
image = preprocess_input(image)
return image, image_path
def get_max_length(tensor):
return max(len(t) for t in tensor)
def load_image_and_caption(image_name, caption):
image_name = image_name.decode('utf-8').split('/')[-1]
image_tensor = np.load(f'./{image_name}.npy')
return image_tensor, caption
class BahdanauAttention(Model):
def __init__(self, units):
super(BahdanauAttention, self).__init__()
self.W1 = Dense(units)
self.W2 = Dense(units)
self.V = Dense(1)
def call(self, features, hidden):
hidden_with_time_axis = tf.expand_dims(hidden, 1)
score = tf.nn.tanh(self.W1(features) +
self.W2(hidden_with_time_axis))
attention_w = tf.nn.softmax(self.V(score), axis=1)
ctx_vector = attention_w * features
ctx_vector = tf.reduce_sum(ctx_vector, axis=1)
return ctx_vector, attention_w
class CNNEncoder(Model):
def __init__(self, embedding_dim):
super(CNNEncoder, self).__init__()
self.fc = Dense(embedding_dim)
def call(self, x):
x = self.fc(x)
x = tf.nn.relu(x)
return x
class RNNDecoder(Model):
def __init__(self, embedding_size, units, vocab_size):
super(RNNDecoder, self).__init__()
self.units = units
self.embedding = Embedding(vocab_size, embedding_size)
self.gru = GRU(self.units,
return_sequences=True,
return_state=True,
recurrent_initializer='glorot_uniform')
self.fc1 = Dense(self.units)
self.fc2 = Dense(vocab_size)
self.attention = BahdanauAttention(self.units)
def call(self, x, features, hidden):
context_vector, attention_weights = \
self.attention(features, hidden)
x = self.embedding(x)
expanded_context = tf.expand_dims(context_vector, 1)
x = Concatenate(axis=-1)([expanded_context, x])
output, state = self.gru(x)
x = self.fc1(output)
x = tf.reshape(x, (-1, x.shape[2]))
x = self.fc2(x)
return x, state, attention_weights
def reset_state(self, batch_size):
return tf.zeros((batch_size, self.units))
class ImageCaptioner(object):
def __init__(self, embedding_size, units, vocab_size,
tokenizer):
self.tokenizer = tokenizer
self.encoder = CNNEncoder(embedding_size)
self.decoder = RNNDecoder(embedding_size, units,
vocab_size)
self.optimizer = Adam()
self.loss = SparseCategoricalCrossentropy(
from_logits=True,
reduction='none')
def loss_function(self, real, predicted):
mask = tf.math.logical_not(tf.math.equal(real, 0))
_loss = self.loss(real, predicted)
mask = tf.cast(mask, dtype=_loss.dtype)
_loss *= mask
return tf.reduce_mean(_loss)
@tf.function
def train_step(self, image_tensor, target):
loss = 0
hidden = self.decoder.reset_state(target.shape[0])
start_token_idx = self.tokenizer.word_index['<start>']
init_batch = [start_token_idx] * target.shape[0]
decoder_input = tf.expand_dims(init_batch, 1)
with tf.GradientTape() as tape:
features = self.encoder(image_tensor)
for i in range(1, target.shape[1]):
preds, hidden, _ = self.decoder(decoder_input,
features,
hidden)
loss += self.loss_function(target[:, i],
preds)
decoder_input = tf.expand_dims(target[:, i], 1)
total_loss = loss / int(target.shape[1])
trainable_vars = (self.encoder.trainable_variables +
self.decoder.trainable_variables)
gradients = tape.gradient(loss, trainable_vars)
self.optimizer.apply_gradients(zip(gradients,
trainable_vars))
return loss, total_loss
def train(self, dataset, epochs, num_steps):
for epoch in range(epochs):
start = time.time()
total_loss = 0
for batch, (image_tensor, target) \
in enumerate(dataset):
batch_loss, step_loss = \
self.train_step(image_tensor, target)
total_loss += step_loss
if batch % 100 == 0:
loss = batch_loss.numpy()
loss = loss / int(target.shape[1])
print(f'Epoch {epoch + 1}, batch {batch},'
f' loss {loss:.4f}')
print(f'Epoch {epoch + 1},'
f' loss {total_loss / num_steps:.6f}')
epoch_time = time.time() - start
print(f'Time taken: {epoch_time} seconds. \n')
# Download caption annotation files
INPUT_DIR = os.path.abspath('.')
annots_folder = '/annotations/'
if not os.path.exists(INPUT_DIR + annots_folder):
origin_url = ('http://images.cocodataset.org/annotations'
'/annotations_trainval2014.zip')
cache_subdir = os.path.abspath('.')
annots_zip = get_file('all_captions.zip',
cache_subdir=cache_subdir,
origin=origin_url,
extract=True)
annots_file = (os.path.dirname(annots_zip) +
'/annotations/captions_train2014.json')
os.remove(annots_zip)
else:
annots_file = (INPUT_DIR +
'/annotations/captions_train2014.json')
# Download image files
image_folder = '/train2014/'
if not os.path.exists(INPUT_DIR + image_folder):
origin_url = ('http://images.cocodataset.org/zips/'
'train2014.zip')
cache_subdir = os.path.abspath('.')
image_zip = get_file('train2014.zip',
cache_subdir=cache_subdir,
origin=origin_url,
extract=True)
PATH = os.path.dirname(image_zip) + image_folder
os.remove(image_zip)
else:
PATH = INPUT_DIR + image_folder
# Read the JSON file
with open(annots_file, 'r') as f:
annotations = json.load(f)
# Store all_captions and image names in vectors
captions = []
image_paths = []
for annotation in annotations['annotations']:
caption = '<start>' + annotation['caption'] + ' <end>'
image_id = annotation['image_id']
image_path = f'{PATH}COCO_train2014_{image_id:012d}.jpg'
image_paths.append(image_path)
captions.append(caption)
train_captions, train_img_paths = shuffle(captions,
image_paths,
random_state=42)
SAMPLE_SIZE = 30000
train_captions = train_captions[:SAMPLE_SIZE]
train_img_paths = train_img_paths[:SAMPLE_SIZE]
train_images = sorted(set(train_img_paths))
feature_extractor = InceptionV3(include_top=False,
weights='imagenet')
feature_extractor = Model(feature_extractor.input,
feature_extractor.layers[-1].output)
BATCH_SIZE = 8
image_dataset = (tf.data.Dataset
.from_tensor_slices(train_images)
.map(load_image, num_parallel_calls=AUTOTUNE)
.batch(BATCH_SIZE))
for image, path in image_dataset:
batch_features = feature_extractor.predict(image)
batch_features = tf.reshape(batch_features,
(batch_features.shape[0],
-1,
batch_features.shape[3]))
for batch_feature, p in zip(batch_features, path):
feature_path = p.numpy().decode('UTF-8')
image_name = feature_path.split('/')[-1]
np.save(f'./{image_name}', batch_feature.numpy())
top_k = 5000
filters = '!"#$%&()*+.,-/:;=?@[\]^_`{|}~ '
tokenizer = Tokenizer(num_words=top_k,
oov_token='<unk>',
filters=filters)
tokenizer.fit_on_texts(train_captions)
tokenizer.word_index['<pad>'] = 0
tokenizer.index_word[0] = '<pad>'
train_seqs = tokenizer.texts_to_sequences(train_captions)
captions_seqs = pad_sequences(train_seqs, padding='post')
max_length = get_max_length(train_seqs)
(images_train, images_val, caption_train, caption_val) = \
train_test_split(train_img_paths,
captions_seqs,
test_size=0.2,
random_state=42)
BATCH_SIZE = 64
BUFFER_SIZE = 1000
dataset = (tf.data.Dataset
.from_tensor_slices((images_train, caption_train))
.map(lambda i1, i2:
tf.numpy_function(
load_image_and_caption,
[i1, i2],
[tf.float32, tf.int32]),
num_parallel_calls=AUTOTUNE)
.shuffle(BUFFER_SIZE)
.batch(BATCH_SIZE)
.prefetch(buffer_size=AUTOTUNE))
image_captioner = ImageCaptioner(embedding_size=256,
units=512,
vocab_size=top_k + 1,
tokenizer=tokenizer)
EPOCHS = 30
num_steps = len(images_train) // BATCH_SIZE
image_captioner.train(dataset, EPOCHS, num_steps)
def evaluate(encoder, decoder, tokenizer, image, max_length,
attention_shape):
attention_plot = np.zeros((max_length,
attention_shape))
hidden = decoder.reset_state(batch_size=1)
temp_input = tf.expand_dims(load_image(image)[0], 0)
image_tensor_val = feature_extractor(temp_input)
image_tensor_val = tf.reshape(image_tensor_val,
(image_tensor_val.shape[0],
-1,
image_tensor_val.shape[3]))
feats = encoder(image_tensor_val)
start_token_idx = tokenizer.word_index['<start>']
dec_input = tf.expand_dims([start_token_idx], 0)
result = []
for i in range(max_length):
(preds, hidden, attention_w) = \
decoder(dec_input, feats, hidden)
attention_plot[i] = tf.reshape(attention_w,
(-1,)).numpy()
pred_id = tf.random.categorical(preds,
1)[0][0].numpy()
result.append(tokenizer.index_word[pred_id])
if tokenizer.index_word[pred_id] == '<end>':
return result, attention_plot
dec_input = tf.expand_dims([pred_id], 0)
attention_plot = attention_plot[:len(result), :]
return result, attention_plot
def plot_attention(image, result,
attention_plot, output_path):
tmp_image = np.array(load_image(image)[0])
fig = plt.figure(figsize=(10, 10))
for l in range(len(result)):
temp_att = np.resize(attention_plot[l], (8, 8))
ax = fig.add_subplot(len(result) // 2,
len(result) // 2,
l + 1)
ax.set_title(result[l])
image = ax.imshow(tmp_image)
ax.imshow(temp_att,
cmap='gray',
alpha=0.6,
extent=image.get_extent())
plt.tight_layout()
plt.show()
plt.savefig(output_path)
# Captions on the validation set
attention_feats_shape = 64
for i in range(20):
random_id = np.random.randint(0, len(images_val))
print(f'{i}. {random_id}')
image = images_val[random_id]
actual_caption = ' '.join([tokenizer.index_word[i]
for i in caption_val[random_id]
if i != 0])
actual_caption = (actual_caption
.replace('<start>', '')
.replace('<end>', ''))
result, attention_plot = evaluate(image_captioner.encoder,
image_captioner.decoder,
tokenizer,
image,
max_length,
attention_feats_shape)
predicted_caption = (' '.join(result)
.replace('<start>', '')
.replace('<end>', ''))
print(f'Actual caption: {actual_caption}')
print(f'Predicted caption: {predicted_caption}')
output_path = f'./{i}_attention_plot.png'
plot_attention(image, result, attention_plot, output_path)
print('------')
| [
"numpy.load",
"os.remove",
"tensorflow.reduce_sum",
"numpy.resize",
"sklearn.model_selection.train_test_split",
"tensorflow.reshape",
"matplotlib.pyplot.figure",
"tensorflow.numpy_function",
"matplotlib.pyplot.tight_layout",
"tensorflow.keras.losses.SparseCategoricalCrossentropy",
"os.path.abspa... | [((5864, 5884), 'os.path.abspath', 'os.path.abspath', (['"""."""'], {}), "('.')\n", (5879, 5884), False, 'import os\n'), ((7536, 7583), 'sklearn.utils.shuffle', 'shuffle', (['captions', 'image_paths'], {'random_state': '(42)'}), '(captions, image_paths, random_state=42)\n', (7543, 7583), False, 'from sklearn.utils import shuffle\n'), ((7952, 8019), 'tensorflow.keras.models.Model', 'Model', (['feature_extractor.input', 'feature_extractor.layers[-1].output'], {}), '(feature_extractor.input, feature_extractor.layers[-1].output)\n', (7957, 8019), False, 'from tensorflow.keras.models import Model\n'), ((8818, 8880), 'tensorflow.keras.preprocessing.text.Tokenizer', 'Tokenizer', ([], {'num_words': 'top_k', 'oov_token': '"""<unk>"""', 'filters': 'filters'}), "(num_words=top_k, oov_token='<unk>', filters=filters)\n", (8827, 8880), False, 'from tensorflow.keras.preprocessing.text import Tokenizer\n'), ((9107, 9148), 'tensorflow.keras.preprocessing.sequence.pad_sequences', 'pad_sequences', (['train_seqs'], {'padding': '"""post"""'}), "(train_seqs, padding='post')\n", (9120, 9148), False, 'from tensorflow.keras.preprocessing.sequence import pad_sequences\n'), ((9254, 9339), 'sklearn.model_selection.train_test_split', 'train_test_split', (['train_img_paths', 'captions_seqs'], {'test_size': '(0.2)', 'random_state': '(42)'}), '(train_img_paths, captions_seqs, test_size=0.2, random_state=42\n )\n', (9270, 9339), False, 'from sklearn.model_selection import train_test_split\n'), ((709, 736), 'tensorflow.io.read_file', 'tf.io.read_file', (['image_path'], {}), '(image_path)\n', (724, 736), True, 'import tensorflow as tf\n'), ((749, 788), 'tensorflow.image.decode_jpeg', 'tf.image.decode_jpeg', (['image'], {'channels': '(3)'}), '(image, channels=3)\n', (769, 788), True, 'import tensorflow as tf\n'), ((801, 835), 'tensorflow.image.resize', 'tf.image.resize', (['image', '(299, 299)'], {}), '(image, (299, 299))\n', (816, 835), True, 'import tensorflow as tf\n'), ((1100, 1130), 'numpy.load', 'np.load', (['f"""./{image_name}.npy"""'], {}), "(f'./{image_name}.npy')\n", (1107, 1130), True, 'import numpy as np\n'), ((5924, 5965), 'os.path.exists', 'os.path.exists', (['(INPUT_DIR + annots_folder)'], {}), '(INPUT_DIR + annots_folder)\n', (5938, 5965), False, 'import os\n'), ((6099, 6119), 'os.path.abspath', 'os.path.abspath', (['"""."""'], {}), "('.')\n", (6114, 6119), False, 'import os\n'), ((6137, 6229), 'tensorflow.keras.utils.get_file', 'get_file', (['"""all_captions.zip"""'], {'cache_subdir': 'cache_subdir', 'origin': 'origin_url', 'extract': '(True)'}), "('all_captions.zip', cache_subdir=cache_subdir, origin=origin_url,\n extract=True)\n", (6145, 6229), False, 'from tensorflow.keras.utils import get_file\n'), ((6416, 6437), 'os.remove', 'os.remove', (['annots_zip'], {}), '(annots_zip)\n', (6425, 6437), False, 'import os\n'), ((6594, 6634), 'os.path.exists', 'os.path.exists', (['(INPUT_DIR + image_folder)'], {}), '(INPUT_DIR + image_folder)\n', (6608, 6634), False, 'import os\n'), ((6746, 6766), 'os.path.abspath', 'os.path.abspath', (['"""."""'], {}), "('.')\n", (6761, 6766), False, 'import os\n'), ((6783, 6872), 'tensorflow.keras.utils.get_file', 'get_file', (['"""train2014.zip"""'], {'cache_subdir': 'cache_subdir', 'origin': 'origin_url', 'extract': '(True)'}), "('train2014.zip', cache_subdir=cache_subdir, origin=origin_url,\n extract=True)\n", (6791, 6872), False, 'from tensorflow.keras.utils import get_file\n'), ((7001, 7021), 'os.remove', 'os.remove', (['image_zip'], {}), '(image_zip)\n', (7010, 7021), False, 'import os\n'), ((7138, 7150), 'json.load', 'json.load', (['f'], {}), '(f)\n', (7147, 7150), False, 'import json\n'), ((8356, 8443), 'tensorflow.reshape', 'tf.reshape', (['batch_features', '(batch_features.shape[0], -1, batch_features.shape[3])'], {}), '(batch_features, (batch_features.shape[0], -1, batch_features.\n shape[3]))\n', (8366, 8443), True, 'import tensorflow as tf\n'), ((10289, 10328), 'numpy.zeros', 'np.zeros', (['(max_length, attention_shape)'], {}), '((max_length, attention_shape))\n', (10297, 10328), True, 'import numpy as np\n'), ((10542, 10634), 'tensorflow.reshape', 'tf.reshape', (['image_tensor_val', '(image_tensor_val.shape[0], -1, image_tensor_val.shape[3])'], {}), '(image_tensor_val, (image_tensor_val.shape[0], -1,\n image_tensor_val.shape[3]))\n', (10552, 10634), True, 'import tensorflow as tf\n'), ((10845, 10881), 'tensorflow.expand_dims', 'tf.expand_dims', (['[start_token_idx]', '(0)'], {}), '([start_token_idx], 0)\n', (10859, 10881), True, 'import tensorflow as tf\n'), ((11660, 11688), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(10, 10)'}), '(figsize=(10, 10))\n', (11670, 11688), True, 'import matplotlib.pyplot as plt\n'), ((12117, 12135), 'matplotlib.pyplot.tight_layout', 'plt.tight_layout', ([], {}), '()\n', (12133, 12135), True, 'import matplotlib.pyplot as plt\n'), ((12140, 12150), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (12148, 12150), True, 'import matplotlib.pyplot as plt\n'), ((12155, 12179), 'matplotlib.pyplot.savefig', 'plt.savefig', (['output_path'], {}), '(output_path)\n', (12166, 12179), True, 'import matplotlib.pyplot as plt\n'), ((1438, 1463), 'tensorflow.expand_dims', 'tf.expand_dims', (['hidden', '(1)'], {}), '(hidden, 1)\n', (1452, 1463), True, 'import tensorflow as tf\n'), ((1697, 1730), 'tensorflow.reduce_sum', 'tf.reduce_sum', (['ctx_vector'], {'axis': '(1)'}), '(ctx_vector, axis=1)\n', (1710, 1730), True, 'import tensorflow as tf\n'), ((1978, 1991), 'tensorflow.nn.relu', 'tf.nn.relu', (['x'], {}), '(x)\n', (1988, 1991), True, 'import tensorflow as tf\n'), ((2738, 2771), 'tensorflow.expand_dims', 'tf.expand_dims', (['context_vector', '(1)'], {}), '(context_vector, 1)\n', (2752, 2771), True, 'import tensorflow as tf\n'), ((2907, 2938), 'tensorflow.reshape', 'tf.reshape', (['x', '(-1, x.shape[2])'], {}), '(x, (-1, x.shape[2]))\n', (2917, 2938), True, 'import tensorflow as tf\n'), ((3062, 3096), 'tensorflow.zeros', 'tf.zeros', (['(batch_size, self.units)'], {}), '((batch_size, self.units))\n', (3070, 3096), True, 'import tensorflow as tf\n'), ((3430, 3436), 'tensorflow.keras.optimizers.Adam', 'Adam', ([], {}), '()\n', (3434, 3436), False, 'from tensorflow.keras.optimizers import Adam\n'), ((3457, 3522), 'tensorflow.keras.losses.SparseCategoricalCrossentropy', 'SparseCategoricalCrossentropy', ([], {'from_logits': '(True)', 'reduction': '"""none"""'}), "(from_logits=True, reduction='none')\n", (3486, 3522), False, 'from tensorflow.keras.losses import SparseCategoricalCrossentropy\n'), ((3713, 3745), 'tensorflow.cast', 'tf.cast', (['mask'], {'dtype': '_loss.dtype'}), '(mask, dtype=_loss.dtype)\n', (3720, 3745), True, 'import tensorflow as tf\n'), ((3784, 3805), 'tensorflow.reduce_mean', 'tf.reduce_mean', (['_loss'], {}), '(_loss)\n', (3798, 3805), True, 'import tensorflow as tf\n'), ((4093, 4122), 'tensorflow.expand_dims', 'tf.expand_dims', (['init_batch', '(1)'], {}), '(init_batch, 1)\n', (4107, 4122), True, 'import tensorflow as tf\n'), ((6323, 6350), 'os.path.dirname', 'os.path.dirname', (['annots_zip'], {}), '(annots_zip)\n', (6338, 6350), False, 'import os\n'), ((6955, 6981), 'os.path.dirname', 'os.path.dirname', (['image_zip'], {}), '(image_zip)\n', (6970, 6981), False, 'import os\n'), ((11400, 11428), 'tensorflow.expand_dims', 'tf.expand_dims', (['[pred_id]', '(0)'], {}), '([pred_id], 0)\n', (11414, 11428), True, 'import tensorflow as tf\n'), ((11742, 11778), 'numpy.resize', 'np.resize', (['attention_plot[l]', '(8, 8)'], {}), '(attention_plot[l], (8, 8))\n', (11751, 11778), True, 'import numpy as np\n'), ((3630, 3652), 'tensorflow.math.equal', 'tf.math.equal', (['real', '(0)'], {}), '(real, 0)\n', (3643, 3652), True, 'import tensorflow as tf\n'), ((4137, 4154), 'tensorflow.GradientTape', 'tf.GradientTape', ([], {}), '()\n', (4152, 4154), True, 'import tensorflow as tf\n'), ((5092, 5103), 'time.time', 'time.time', ([], {}), '()\n', (5101, 5103), False, 'import time\n'), ((4579, 4610), 'tensorflow.expand_dims', 'tf.expand_dims', (['target[:, i]', '(1)'], {}), '(target[:, i], 1)\n', (4593, 4610), True, 'import tensorflow as tf\n'), ((5735, 5746), 'time.time', 'time.time', ([], {}), '()\n', (5744, 5746), False, 'import time\n'), ((8079, 8127), 'tensorflow.data.Dataset.from_tensor_slices', 'tf.data.Dataset.from_tensor_slices', (['train_images'], {}), '(train_images)\n', (8113, 8127), True, 'import tensorflow as tf\n'), ((11047, 11077), 'tensorflow.reshape', 'tf.reshape', (['attention_w', '(-1,)'], {}), '(attention_w, (-1,))\n', (11057, 11077), True, 'import tensorflow as tf\n'), ((11144, 11175), 'tensorflow.random.categorical', 'tf.random.categorical', (['preds', '(1)'], {}), '(preds, 1)\n', (11165, 11175), True, 'import tensorflow as tf\n'), ((9445, 9510), 'tensorflow.data.Dataset.from_tensor_slices', 'tf.data.Dataset.from_tensor_slices', (['(images_train, caption_train)'], {}), '((images_train, caption_train))\n', (9479, 9510), True, 'import tensorflow as tf\n'), ((9570, 9645), 'tensorflow.numpy_function', 'tf.numpy_function', (['load_image_and_caption', '[i1, i2]', '[tf.float32, tf.int32]'], {}), '(load_image_and_caption, [i1, i2], [tf.float32, tf.int32])\n', (9587, 9645), True, 'import tensorflow as tf\n')] |
# -*- coding: utf-8 -*-
"""
File Name: reader
Description :
Author : mick.yi
date: 2019/3/14
"""
import numpy as np
import os
import glob
def load_annotation(annotation_path, image_dir):
"""
加载标注信息
:param annotation_path:
:param image_dir:
:return:
"""
image_annotation = {}
# 文件名称,路径
# base_name = os.path.basename(annotation_path)
_, base_name = os.path.split(annotation_path)
base_name, _ = os.path.splitext(base_name)
# image_name = base_name # 通配符 gt_img_3.txt,img_3.jpg or png
image_annotation["annotation_path"] = annotation_path
image_annotation["image_path"] = os.sep.join([image_dir, base_name+".jpg"])
image_annotation["file_name"] = os.path.basename(image_annotation["image_path"]) # 图像文件名
# 读取边框标注
bbox = []
quadrilateral = [] # 四边形
with open(annotation_path, "r", encoding='utf-8') as f:
lines = f.read().encode('utf-8').decode('utf-8-sig').splitlines()
# lines = f.readlines()
# print(lines)
for line in lines:
line = line.strip().split(",")
# 左上、右上、右下、左下 四个坐标 如:377,117,463,117,465,130,378,130
lt_x, lt_y, rt_x, rt_y, rb_x, rb_y, lb_x, lb_y = map(float, line[:8])
x_min, y_min, x_max, y_max = min(lt_x, lb_x), min(lt_y, rt_y), max(rt_x, rb_x), max(lb_y, rb_y)
bbox.append([y_min, x_min, y_max, x_max])
quadrilateral.append([lt_x, lt_y, rt_x, rt_y, rb_x, rb_y, lb_x, lb_y])
image_annotation["boxes"] = np.asarray(bbox, np.float32).reshape((-1, 4))
image_annotation["quadrilaterals"] = np.asarray(quadrilateral, np.float32).reshape((-1, 8))
image_annotation["labels"] = np.ones(shape=(len(bbox)), dtype=np.uint8)
return image_annotation
| [
"os.path.basename",
"numpy.asarray",
"os.path.splitext",
"os.sep.join",
"os.path.split"
] | [((443, 473), 'os.path.split', 'os.path.split', (['annotation_path'], {}), '(annotation_path)\n', (456, 473), False, 'import os\n'), ((494, 521), 'os.path.splitext', 'os.path.splitext', (['base_name'], {}), '(base_name)\n', (510, 521), False, 'import os\n'), ((688, 732), 'os.sep.join', 'os.sep.join', (["[image_dir, base_name + '.jpg']"], {}), "([image_dir, base_name + '.jpg'])\n", (699, 732), False, 'import os\n'), ((768, 816), 'os.path.basename', 'os.path.basename', (["image_annotation['image_path']"], {}), "(image_annotation['image_path'])\n", (784, 816), False, 'import os\n'), ((1559, 1587), 'numpy.asarray', 'np.asarray', (['bbox', 'np.float32'], {}), '(bbox, np.float32)\n', (1569, 1587), True, 'import numpy as np\n'), ((1647, 1684), 'numpy.asarray', 'np.asarray', (['quadrilateral', 'np.float32'], {}), '(quadrilateral, np.float32)\n', (1657, 1684), True, 'import numpy as np\n')] |
import numpy as np
import pandas as pd
import os,sys,random
from tqdm import tqdm
from sklearn.metrics import roc_auc_score
from sklearn.metrics import average_precision_score
from sklearn.metrics import precision_recall_curve
from sklearn.metrics import f1_score
from sklearn.metrics import classification_report
from sklearn.model_selection import train_test_split, GridSearchCV
from keras.callbacks import EarlyStopping, ModelCheckpoint
from keras.models import load_model
import tensorflow as tf
import keras
from process_data import *
from feature_selection import *
from model import get_model
from method_config import *
SYNERGY_THRES = 10
BATCH_SIZE = 256
N_EPOCHS = 200
PATIENCE = 30
available_feat_type_list = {'NCI_60':['met','mut','cop','exp']}
available_cancer_specific_cell_list = {'NCI_60':{'TNBC':['MDA-MB-231','MDA-MB-435','BT-549','HS 578T']}}
def prepare_data():
synergy_data = input_synergy_data(config['synergy_data'])
print("synergy data loaded")
cell_data_dicts = input_cellline_data(config['cell_data'])
print("cell line feats loaded")
drug_data_dicts = input_drug_data()
print("drug feats loaded")
# get full drug list and cell line list
drug_list = synergy_data['drug1'].unique().tolist()
cell_list = synergy_data['cell'].unique().tolist()
# filtering data
drug_list = filter_drug(drug_list, config['drug_feat_filter'])
cell_list = filter_cell(cell_list, config['cell_list'], available_cancer_specific_cell_list[config['cell_data']])
synergy_data = synergy_data[(synergy_data['drug1'].isin(drug_list))&(synergy_data['drug2'].isin(drug_list))&(synergy_data['cell'].isin(cell_list))]
# generate matrices for cell line features
cell_feats, selected_cells = filter_cell_features(cell_data_dicts, cell_list, config['cell_feats'], config['cell_feat_filter'], config['cell_integrate'])
synergy_data = synergy_data[synergy_data['cell'].isin(selected_cells)]
print("cell line feats filtered")
print("\n")
print("number of drugs:", len(drug_list))
print("number of cells:", len(selected_cells))
print("number of data:", synergy_data.shape)
print("\n")
if config['cell_integrate'] == True:
# in this case, cell_fets stores a dataframe containing features
X_cell = np.zeros((synergy_data.shape[0], cell_feats.shape[0]))
for i in tqdm(range(synergy_data.shape[0])):
row = synergy_data.iloc[i]
X_cell[i,:] = cell_feats[row['cell']].values
else:
X_cell = {}
for feat_type in config['cell_feats']:
print(feat_type, cell_feats[feat_type].shape[0])
temp_cell = np.zeros((synergy_data.shape[0], cell_feats[feat_type].shape[0]))
for i in tqdm(range(synergy_data.shape[0])):
row = synergy_data.iloc[i]
temp_cell[i,:] = cell_feats[feat_type][row['cell']].values
X_cell[feat_type] = temp_cell
if config['cell_integrate'] == True:
print("cell features: ", X_cell.shape)
else:
print("cell features:", list(X_cell.keys()))
# generate matrices for drug features
# first generate individual data matrices for drug1 and drug2 and different feat types
print("\ngenerating drug feats...")
drug_mat_dict = {}
for feat_type in config['drug_feats']:
if feat_type != "monotherapy":
dim = drug_data_dicts[feat_type].shape[0]
temp_X_1 = np.zeros((synergy_data.shape[0], dim))
temp_X_2 = np.zeros((synergy_data.shape[0], dim))
for i in tqdm(range(synergy_data.shape[0])):
row = synergy_data.iloc[i]
temp_X_1[i,:] = drug_data_dicts[feat_type][int(row['drug1'])]
temp_X_2[i,:] = drug_data_dicts[feat_type][int(row['drug2'])]
else:
dim = 3
temp_X_1 = np.zeros((synergy_data.shape[0], dim))
temp_X_2 = np.zeros((synergy_data.shape[0], dim))
for i in tqdm(range(synergy_data.shape[0])):
row = synergy_data.iloc[i]
temp_X_1[i,:] = drug_data_dicts[feat_type].loc[row['cell'], int(row['drug1'])]
temp_X_2[i,:] = drug_data_dicts[feat_type].loc[row['cell'], int(row['drug2'])]
drug_mat_dict[feat_type+"_1"] = temp_X_1
drug_mat_dict[feat_type+"_2"] = temp_X_2
# now aggregate drug features based on whether they should be summed
X_drug_temp = {}
if config['drug_indep'] == False:
for feat_type in config['drug_feats']:
if feat_type != "monotherapy":
temp_X = drug_mat_dict[feat_type+"_1"] + drug_mat_dict[feat_type+"_2"]
X_drug_temp[feat_type] = temp_X
else:
X_drug_temp[feat_type+"_1"] = drug_mat_dict[feat_type+"_1"]
X_drug_temp[feat_type+"_2"] = drug_mat_dict[feat_type+"_2"]
else:
X_drug_temp = drug_mat_dict
# now aggregate drug features based on whether they should be integrated
if config['drug_integrate'] == False:
X_drug = X_drug_temp
else:
# in this case, drug feature is a numpy array instead of dict of arrays
X_drug = np.concatenate(list(X_drug_temp.values()), axis=1)
if config['drug_integrate'] == True:
print("drug features: ", X_drug.shape)
else:
print("drug features")
print(list(X_drug.keys()))
for key, value in X_drug.items():
print(key, value.shape)
Y = (synergy_data['score']>SYNERGY_THRES).astype(int).values
return X_cell, X_drug, Y
def training(X_cell, X_drug, Y):
indices = np.random.permutation(Y.shape[0])
training_idx, test_idx = indices[:int(0.8*Y.shape[0])], indices[int(0.8*Y.shape[0]):]
#training_idx, test_idx = indices[:int(0.1*Y.shape[0])], indices[int(0.1*Y.shape[0]):int(0.15*Y.shape[0])]
if config['model_name'] != "autoencoder":
model = get_model(config['model_name'])
else:
model, encoders = get_model(config['model_name'])
Y_train, Y_test = Y[training_idx], Y[test_idx]
if config['model_name'] in ['NN','nn_xia_2018','nn_kim_2020']:
model.compile(loss='binary_crossentropy',
optimizer='adam',
metrics=['accuracy'])
callbacks = [EarlyStopping(monitor='val_loss', patience=PATIENCE),
ModelCheckpoint(filepath='best_model_%s.h5' % config['model_name'], monitor='val_loss', save_best_only=True)]
if config['model_name'] == 'NN':
X = np.concatenate([X_cell,X_drug], axis=1)
X_train, X_test = X[training_idx], X[test_idx]
_ = model.fit(X_train, Y_train,
batch_size=BATCH_SIZE,
epochs=N_EPOCHS,
verbose=1,
validation_split=0.1,
callbacks=callbacks)
elif config['model_name'] == 'nn_xia_2018':
X_train, X_test = {}, {}
for key,value in X_cell.items():
X_train[key] = value[training_idx]
X_test[key] = value[test_idx]
for key,value in X_drug.items():
X_train[key] = value[training_idx]
X_test[key] = value[test_idx]
_ = model.fit(
{'exp':X_train['exp'], 'mir':X_train['mir'], 'pro':X_train['pro'],
'drug1':X_train['morgan_fingerprint_1'], 'drug2':X_train['morgan_fingerprint_2']},
Y_train,
batch_size=BATCH_SIZE,
epochs=N_EPOCHS,
verbose=1,
validation_split=0.1,
callbacks=callbacks
)
elif config['model_name'] == 'nn_kim_2020':
X_train, X_test = {}, {}
X_train['exp'] = X_cell[training_idx]
X_test['exp'] = X_cell[test_idx]
for key,value in X_drug.items():
X_train[key] = value[training_idx]
X_test[key] = value[test_idx]
_ = model.fit(
{'exp':X_train['exp'], 'fingerprint_1':X_train['morgan_fingerprint_1'], 'fingerprint_2':X_train['morgan_fingerprint_2'],
'target_1':X_train['drug_target_1'], 'target_2':X_train['drug_target_2']},
Y_train,
batch_size=BATCH_SIZE,
epochs=N_EPOCHS,
verbose=1,
validation_split=0.1,
callbacks=callbacks
)
model = load_model('best_model_%s.h5' % config['model_name'])
elif config['model_name'] == "autoencoder":
model.compile(optimizer='adam', loss=['mse','mse', 'mse'])
X_train, X_test = {}, {}
for key,value in X_cell.items():
X_train[key] = value[training_idx]
X_test[key] = value[test_idx]
X_train['morgan_fingerprint'] = X_drug[training_idx]
X_test['morgan_fingerprint'] = X_drug[test_idx]
_ = model.fit(
[X_train['exp'], X_train['mut'], X_train['cop']],
[X_train['exp'], X_train['mut'], X_train['cop']],
batch_size=BATCH_SIZE,
epochs=20,
verbose=1
)
encoded_train_exp = encoders[0].predict(X_train['exp'])
encoded_train_mut = encoders[1].predict(X_train['mut'])
encoded_train_cop = encoders[2].predict(X_train['cop'])
encoded_train_X = np.concatenate([encoded_train_exp,encoded_train_mut,encoded_train_cop,
X_train['morgan_fingerprint']], axis=1)
print("encoded_train_X:",encoded_train_X.shape)
encoded_test_exp = encoders[0].predict(X_test['exp'])
encoded_test_mut = encoders[1].predict(X_test['mut'])
encoded_test_cop = encoders[2].predict(X_test['cop'])
encoded_test_X = np.concatenate([encoded_test_exp,encoded_test_mut,encoded_test_cop,
X_test['morgan_fingerprint']], axis=1)
X_test = encoded_test_X
model = get_model("autoencoder_NN")
model.compile(loss='binary_crossentropy',
optimizer='adam',
metrics=['accuracy'])
_ = model.fit(encoded_train_X, Y_train,
batch_size=BATCH_SIZE,
epochs=100,
verbose=1)
else:
X = np.concatenate([X_cell,X_drug], axis=1)
X_train, X_test = X[training_idx], X[test_idx]
model.fit(X_train, Y_train)
return model, X_test, Y_test
def evaluate(model, X_test, Y_test):
if config['model_name'] in ['NN','nn_xia_2018','nn_kim_2020']:
if config['model_name'] == 'NN':
pred = model.predict(X_test)
elif config['model_name'] == 'nn_xia_2018':
pred = model.predict({'exp':X_test['exp'], 'mir':X_test['mir'], 'pro':X_test['pro'],
'drug1':X_test['morgan_fingerprint_1'], 'drug2':X_test['morgan_fingerprint_2']})
elif config['model_name'] == 'nn_kim_2020':
pred = model.predict({'exp':X_test['exp'], 'fingerprint_1':X_test['morgan_fingerprint_1'], 'fingerprint_2':X_test['morgan_fingerprint_2'],
'target_1':X_test['drug_target_1'], 'target_2':X_test['drug_target_2']})
elif config['model_name'] == "autoencoder":
pred = model.predict(X_test)
else:
pred = model.predict_proba(X_test)[:,1]
auc = roc_auc_score(Y_test, pred)
ap = average_precision_score(Y_test, pred)
f1 = f1_score(Y_test, np.round(pred))
val_results = {'AUC':auc, 'AUPR':ap, 'f1':f1, 'Y_test':Y_test.tolist(), 'Y_pred':pred.tolist()}
return val_results
def main(method):
X_cell, X_drug, Y = prepare_data()
print("data loaded")
model, X_test, Y_test = training(X_cell, X_drug, Y)
print("training finished")
val_results = evaluate(model, X_test, Y_test)
# save results
rand_num = random.randint(1,1000000)
with open("results/%s_%s.json"%(method, str(rand_num)), "w") as f:
json.dump(val_results, f)
if __name__ == "__main__":
method = sys.argv[1]
# this is a global variable
config = method_config_dict[method]
print(method, config)
main(method) | [
"keras.models.load_model",
"random.randint",
"model.get_model",
"keras.callbacks.ModelCheckpoint",
"numpy.zeros",
"sklearn.metrics.roc_auc_score",
"keras.callbacks.EarlyStopping",
"numpy.random.permutation",
"sklearn.metrics.average_precision_score",
"numpy.round",
"numpy.concatenate"
] | [((5653, 5686), 'numpy.random.permutation', 'np.random.permutation', (['Y.shape[0]'], {}), '(Y.shape[0])\n', (5674, 5686), True, 'import numpy as np\n'), ((11557, 11584), 'sklearn.metrics.roc_auc_score', 'roc_auc_score', (['Y_test', 'pred'], {}), '(Y_test, pred)\n', (11570, 11584), False, 'from sklearn.metrics import roc_auc_score\n'), ((11594, 11631), 'sklearn.metrics.average_precision_score', 'average_precision_score', (['Y_test', 'pred'], {}), '(Y_test, pred)\n', (11617, 11631), False, 'from sklearn.metrics import average_precision_score\n'), ((12056, 12082), 'random.randint', 'random.randint', (['(1)', '(1000000)'], {}), '(1, 1000000)\n', (12070, 12082), False, 'import os, sys, random\n'), ((2302, 2356), 'numpy.zeros', 'np.zeros', (['(synergy_data.shape[0], cell_feats.shape[0])'], {}), '((synergy_data.shape[0], cell_feats.shape[0]))\n', (2310, 2356), True, 'import numpy as np\n'), ((5951, 5982), 'model.get_model', 'get_model', (["config['model_name']"], {}), "(config['model_name'])\n", (5960, 5982), False, 'from model import get_model\n'), ((6019, 6050), 'model.get_model', 'get_model', (["config['model_name']"], {}), "(config['model_name'])\n", (6028, 6050), False, 'from model import get_model\n'), ((8569, 8622), 'keras.models.load_model', 'load_model', (["('best_model_%s.h5' % config['model_name'])"], {}), "('best_model_%s.h5' % config['model_name'])\n", (8579, 8622), False, 'from keras.models import load_model\n'), ((11658, 11672), 'numpy.round', 'np.round', (['pred'], {}), '(pred)\n', (11666, 11672), True, 'import numpy as np\n'), ((2668, 2733), 'numpy.zeros', 'np.zeros', (['(synergy_data.shape[0], cell_feats[feat_type].shape[0])'], {}), '((synergy_data.shape[0], cell_feats[feat_type].shape[0]))\n', (2676, 2733), True, 'import numpy as np\n'), ((3465, 3503), 'numpy.zeros', 'np.zeros', (['(synergy_data.shape[0], dim)'], {}), '((synergy_data.shape[0], dim))\n', (3473, 3503), True, 'import numpy as np\n'), ((3527, 3565), 'numpy.zeros', 'np.zeros', (['(synergy_data.shape[0], dim)'], {}), '((synergy_data.shape[0], dim))\n', (3535, 3565), True, 'import numpy as np\n'), ((3879, 3917), 'numpy.zeros', 'np.zeros', (['(synergy_data.shape[0], dim)'], {}), '((synergy_data.shape[0], dim))\n', (3887, 3917), True, 'import numpy as np\n'), ((3941, 3979), 'numpy.zeros', 'np.zeros', (['(synergy_data.shape[0], dim)'], {}), '((synergy_data.shape[0], dim))\n', (3949, 3979), True, 'import numpy as np\n'), ((6326, 6378), 'keras.callbacks.EarlyStopping', 'EarlyStopping', ([], {'monitor': '"""val_loss"""', 'patience': 'PATIENCE'}), "(monitor='val_loss', patience=PATIENCE)\n", (6339, 6378), False, 'from keras.callbacks import EarlyStopping, ModelCheckpoint\n'), ((6401, 6514), 'keras.callbacks.ModelCheckpoint', 'ModelCheckpoint', ([], {'filepath': "('best_model_%s.h5' % config['model_name'])", 'monitor': '"""val_loss"""', 'save_best_only': '(True)'}), "(filepath='best_model_%s.h5' % config['model_name'], monitor\n ='val_loss', save_best_only=True)\n", (6416, 6514), False, 'from keras.callbacks import EarlyStopping, ModelCheckpoint\n'), ((6569, 6609), 'numpy.concatenate', 'np.concatenate', (['[X_cell, X_drug]'], {'axis': '(1)'}), '([X_cell, X_drug], axis=1)\n', (6583, 6609), True, 'import numpy as np\n'), ((9476, 9592), 'numpy.concatenate', 'np.concatenate', (["[encoded_train_exp, encoded_train_mut, encoded_train_cop, X_train[\n 'morgan_fingerprint']]"], {'axis': '(1)'}), "([encoded_train_exp, encoded_train_mut, encoded_train_cop,\n X_train['morgan_fingerprint']], axis=1)\n", (9490, 9592), True, 'import numpy as np\n'), ((9917, 10029), 'numpy.concatenate', 'np.concatenate', (["[encoded_test_exp, encoded_test_mut, encoded_test_cop, X_test[\n 'morgan_fingerprint']]"], {'axis': '(1)'}), "([encoded_test_exp, encoded_test_mut, encoded_test_cop,\n X_test['morgan_fingerprint']], axis=1)\n", (9931, 10029), True, 'import numpy as np\n'), ((10125, 10152), 'model.get_model', 'get_model', (['"""autoencoder_NN"""'], {}), "('autoencoder_NN')\n", (10134, 10152), False, 'from model import get_model\n'), ((10484, 10524), 'numpy.concatenate', 'np.concatenate', (['[X_cell, X_drug]'], {'axis': '(1)'}), '([X_cell, X_drug], axis=1)\n', (10498, 10524), True, 'import numpy as np\n')] |
import numpy as np
def gen_toy_data(samples, dim):
rng = np.random.RandomState(37)
x = rng.rand(samples, dim)
y = 10 * x.dot(rng.random(dim)) + 3 * rng.rand(samples)
return x, y
| [
"numpy.random.RandomState"
] | [((63, 88), 'numpy.random.RandomState', 'np.random.RandomState', (['(37)'], {}), '(37)\n', (84, 88), True, 'import numpy as np\n')] |
import logging
from astropy import units as u
import numpy as np
import matplotlib.pyplot as plt
from scipy import interpolate
from astropy.coordinates import SkyCoord
from astropy.coordinates import Angle
try:
from extinction import fm07 as extinction_law
except ModuleNotFoundError:
# Error handling
pass
try:
from dustmaps.marshall import MarshallQuery
from dustmaps.bayestar import BayestarQuery
from dustmaps.bayestar import BayestarWebQuery
except ModuleNotFoundError:
# Error handling
pass
try:
import statsmodels.api as sm
except ModuleNotFoundError:
# Error handling
pass
from scipy.interpolate import interp1d
from scipy import stats
import seaborn as sns
pal = sns.color_palette("colorblind")
from seaborn.algorithms import bootstrap
import pandas as pd
def kinematic_distance_flat(l, v, R_sun = 8.12 * u.kpc, v_sun = 220 * u.km/u.s):
term1 = R_sun * np.cos(l*u.deg)
r = R_sun * np.sin(l*u.deg) * v_sun / (v*u.km/u.s + v_sun * np.sin(l*u.deg))
term2 = np.sqrt(r**2 - (R_sun * np.sin(l*u.deg))**2)
return term1 + term2, term1 - term2
def get_scale_height_data(data, track = None, deredden = False,
return_pandas_dataframe = False,
longitude_mask_width = None,
step_size = None, R_sun = None, v_sun = None,
closer = False, add_kinematic_distance = False, **kwargs):
"""
Return data needed for scale height analysis
Parameters
----------
data: `skySurvey`
WHAM skySurvey object of full sky (requires track keyword), or spiral arm section
track: `str`, optional, must be keyword
if provided, will apply skySurvey.get_spiral_slice for provided track
if None, will check for track as an attribute of data
deredden: `bool`, `dustmap`, optional, must be keyword
if True, will apply dereddening using 3D dustmaps of Marshall et al. (2006)
or can input a dustmap to query from using the dustmaps package
default to `dustmaps.marshall.MarshallQuery`
Warning: Currently only supports Marshall Dustmap
return_pandas_dataframe: `bool`, optional, must be keyword
if True, returns pandas dataframe with subset of data specific to scale height analysis
longitude_mask_width: `number`, `u.Quantity`, optional, must be keyword
if provided, returns list of masks splitting data into sky sections
of given width in degrees
step_size: `number`, `u.Quantity`, optional, must be keyword
if provided, sets step_size for longitude masks
default to half width
R_sun: `u.Quantity`, optional, must be keyword
Sun Galactocentric Distance
v_sun: `u.Quantity`, optional, must be keyword
Sun rotation velocity
add_kinematic_distance: `bool`, optional, must be keyword
if True, adds in kinematic distances using a flat rotation curve
where no parallax ones available
**kwargs: `dict`
keywords passed to data.get_spiral_slice if track is provided
"""
# Check Wrapping
if "wrap_at_180" in kwargs:
if kwargs["wrap_at_180"]:
wrap_at = "180d"
else:
wrap_at = "360d"
else:
wrap_at = "360d"
if add_kinematic_distance:
if R_sun is None:
R_sun = 8.127 * u.kpc
if v_sun is None:
v_sun = 220*u.km/u.s
# Must have return_track
try:
test = np.all(kwargs["return_track"])
except KeyError:
kwargs["return_track"] = True
finally:
if kwargs["return_track"] is False:
kwargs["return_track"] = True
logging.warning("keyword 'return_track' must be set to True!")
# Get / ensure proper track is available
if (track is None):
if not hasattr(data, "lbv_RBD_track"):
raise SyntaxError("No track provided - distance information is required")
else:
data, data.lbv_RBD_track = data.get_spiral_slice(track = track, **kwargs)
if data.lbv_RBD_track.shape[1] < 3:
raise ValueError("provided track does not have distance information!")
if add_kinematic_distance:
distance_is_none = data.lbv_RBD_track[:,-1] == 0.0
if distance_is_none.sum() > 0:
distances_1, distances_2 = kinematic_distance_flat(data.lbv_RBD_track[distance_is_none,0],
data.lbv_RBD_track[distance_is_none,1], R_sun = R_sun, v_sun = v_sun)
if closer:
neg_dist = distances_2 < 0.
distances_2[neg_dist] = distances_1[neg_dist]
data.lbv_RBD_track[distance_is_none,-1] = distances_2
else:
data.lbv_RBD_track[distance_is_none,-1] = distances_1
# Setup dustmaps if needed
if deredden.__class__ is bool:
if deredden:
deredden = MarshallQuery()
elif not hasattr(deredden, "query"):
raise TypeError("invaled dustmap provided - must provide a dustmap class that can query or set to \
True to set defualt dustmap to MarshallQuery.")
data["tan(b)"] = np.tan(data["GAL-LAT"].data*u.deg)
# Apply dereddening
if not deredden.__class__ is bool:
# Get all distances assuming plane parallel
distance_interpolator = interpolate.interp1d(Angle(data.lbv_RBD_track[:,0]*u.deg).wrap_at(wrap_at),
data.lbv_RBD_track[:,-1])
distances = distance_interpolator(Angle(data["GAL-LON"].data*u.deg).wrap_at(wrap_at))
coordinates = data.get_SkyCoord(distance = distances * u.kpc)
if (deredden.__class__ is BayestarQuery) | (deredden.__class__ is BayestarWebQuery):
Av_bayestar = 2.742 * deredden(coordinates)
wave_ha = np.array([6562.8])
A_V_to_A_ha = extinction_law(wave_ha, 1.)
data["DISTANCE"] = distances * u.kpc
data["Z"] = data["DISTANCE"] * data["tan(b)"]
data["Av"] = Av_bayestar
data["INTEN_DERED"] = data["INTEN"][:]
data["INTEN_DERED"][~np.isnan(Av_bayestar)] = \
data["INTEN"][~np.isnan(Av_bayestar)] * 10**(0.4 * A_V_to_A_ha * Av_bayestar[~np.isnan(Av_bayestar)])
else:
# Get A_Ks
AKs = deredden(coordinates)
wave_Ks = 2.17 *u.micron
A_KS_to_A_v = 1. / extinction_law(np.array([wave_Ks.to(u.AA).value]), 1.)
wave_ha = np.array([6562.8])
A_V_to_A_ha = extinction_law(wave_ha, 1.)
data["DISTANCE"] = distances * u.kpc
data["Z"] = data["DISTANCE"] * data["tan(b)"]
data["Av"] = A_KS_to_A_v * AKs
data["INTEN_DERED"] = data["INTEN"][:]
data["INTEN_DERED"][~np.isnan(AKs)] = \
data["INTEN"][~np.isnan(AKs)] * 10**(0.4 * A_V_to_A_ha * A_KS_to_A_v * AKs[~np.isnan(AKs)])
if not longitude_mask_width is None:
if not isinstance(longitude_mask_width, u.Quantity):
longitude_mask_width *= u.deg
logging.warning("No units provided for longitude_mask_width, assuming u.deg.")
if step_size is None:
step_size = longitude_mask_width / 2.
elif not isinstance(step_size, u.Quantity):
step_size *= u.deg
logging.warning("No units provided for step_size, assuming u.deg.")
# Construct masks
wrapped_lon = Angle(data["GAL-LON"]).wrap_at(wrap_at)
lon_range = np.min(wrapped_lon), np.max(wrapped_lon)
n_steps = int(np.ceil(np.round(lon_range[1] - lon_range[0]) / step_size))
lon_edge = np.linspace(lon_range[0], lon_range[1], n_steps)
lon_edges = np.zeros((len(lon_edge)-1, 2)) * u.deg
lon_edges[:,0] = lon_edge[:-1]
lon_edges[:,1] = lon_edge[:-1] + longitude_mask_width
masks = [((wrapped_lon < lon_upper) & (wrapped_lon >= lon_lower)) \
for (lon_lower, lon_upper) in lon_edges]
if return_pandas_dataframe:
try:
df = pd.DataFrame({
"INTEN":data["INTEN"].byteswap().newbyteorder(),
"INTEN_DERED":data["INTEN_DERED"].byteswap().newbyteorder(),
"tan(b)":data["tan(b)"].byteswap().newbyteorder(),
"GAL-LON":data["GAL-LON"].byteswap().newbyteorder(),
"GAL-LAT":data["GAL-LAT"].byteswap().newbyteorder(),
"Av":data["Av"].byteswap().newbyteorder(),
"DISTANCE":data["DISTANCE"],
"Z":data["Z"]
})
except KeyError:
df = pd.DataFrame({
"INTEN":data["INTEN"].byteswap().newbyteorder(),
"tan(b)":data["tan(b)"].byteswap().newbyteorder(),
"GAL-LON":data["GAL-LON"].byteswap().newbyteorder(),
"GAL-LAT":data["GAL-LAT"].byteswap().newbyteorder(),
})
if longitude_mask_width is None:
return data, df
else:
return data, df, masks
else:
return data
def fit_scale_heights(data, masks, min_lat = None, max_lat = None,
deredden = False, fig_names = None, return_smoothed = False,
smoothed_width = None, xlim = None, ylim = None, robust = True,
n_boot = 10000):
"""
Fits scale height data and returns slopes
Parameters
----------
data: `skySurvey`
WHAM skySurvey object of full sky (requires track keyword), or spiral arm section
masks: `list like`
longitude masks to use
min_lat: `u.Quantity`
min latitude to fit
max_lat: `u.Quantity`
max latitude to fit
deredden: `bool`
if True, also fits dereddened slopes
fig_names: `str`
if provided, saves figures following this name
return_smoothed: `bool`
if True, returns smoothed longitude and slope estimates
smoothed_width: `u.Quantity`
width to smooth data to in longitude
robust: `bool`
if True, uses stats.models.robust_linear_model
n_boot: `int`
only if robust = True
number of bootstrap resamples
"""
# Default values
if min_lat is None:
min_lat = 5*u.deg
elif not hasattr(min_lat, "unit"):
min_lat *= u.deg
if max_lat is None:
max_lat = 35*u.deg
elif not hasattr(max_lat, "unit"):
max_lat *= u.deg
if smoothed_width is None:
smoothed_width = 5*u.deg
elif not hasattr(smoothed_width, "unit"):
smoothed_width *= u.deg
#initialize data arrays
slopes_pos = []
slopes_neg = []
slopes_pos_dr = []
slopes_neg_dr = []
intercept_pos = []
intercept_neg = []
intercept_pos_dr = []
intercept_neg_dr = []
slopes_pos_err = []
slopes_neg_err = []
slopes_pos_dr_err = []
slopes_neg_dr_err = []
intercept_pos_err = []
intercept_neg_err = []
intercept_pos_dr_err = []
intercept_neg_dr_err = []
median_longitude = []
median_distance = []
for ell2 in range(len(masks)):
xx = data["tan(b)"][masks[ell2]]
yy = np.log(data["INTEN"][masks[ell2]])
nan_mask = np.isnan(yy)
nan_mask |= np.isinf(yy)
if deredden:
zz = np.log(data["INTEN_DERED"][masks[ell2]])
nan_mask_z = np.isnan(zz)
nan_mask_z |= np.isinf(zz)
median_longitude.append(np.median(data["GAL-LON"][masks[ell2]]))
if deredden:
median_distance.append(np.median(data["DISTANCE"][masks[ell2]]))
y_min = np.tan(min_lat)
y_max = np.tan(max_lat)
if not robust:
if hasattr(stats, "siegelslopes"):
slope_estimator = stats.siegelslopes
else:
logging.warning("Installed version of scipy does not have the siegelslopes method in scipy.stats!")
slope_estimator = stats.theilslopes
siegel_result_pos = slope_estimator(yy[(xx > y_min) & (xx < y_max) & ~nan_mask],
xx[(xx > y_min) & (xx < y_max) & ~nan_mask])
siegel_result_neg = slope_estimator(yy[(xx < -y_min) & (xx > -y_max) & ~nan_mask],
xx[(xx < -y_min) & (xx > -y_max) & ~nan_mask])
if deredden:
siegel_result_pos_dr = slope_estimator(zz[(xx > y_min) & (xx < y_max) & ~nan_mask_z],
xx[(xx > y_min) & (xx < y_max) & ~nan_mask_z])
siegel_result_neg_dr = slope_estimator(zz[(xx < -y_min) & (xx > -y_max) & ~nan_mask_z],
xx[(xx < -y_min) & (xx > -y_max) & ~nan_mask_z])
slopes_pos.append(siegel_result_pos[0])
slopes_neg.append(siegel_result_neg[0])
intercept_pos.append(siegel_result_pos[1])
intercept_neg.append(siegel_result_neg[1])
if deredden:
slopes_pos_dr.append(siegel_result_pos_dr[0])
slopes_neg_dr.append(siegel_result_neg_dr[0])
intercept_pos_dr.append(siegel_result_pos_dr[1])
intercept_neg_dr.append(siegel_result_neg_dr[1])
if fig_names is not None:
figure_name = "{0}_{1}.png".format(fig_names, ell2)
if xlim is None:
xlim = np.array([-0.9, 0.9])
if ylim is None:
ylim = np.array([-4.6, 3.2])
fig = plt.figure()
ax = fig.add_subplot(111)
ax2 = ax.twiny()
ax.scatter(xx,
yy,
color ="k",
alpha = 0.8)
if deredden:
ax.scatter(xx,
zz,
color ="grey",
alpha = 0.8)
ax.set_xlabel(r"$\tan$(b)", fontsize= 12)
ax.set_ylabel(r"$\log$($H\alpha$ Intensity / R)", fontsize= 12)
ax.set_title(r"${0:.1f} < l < {1:.1f}$".format(data["GAL-LON"][masks[ell2]].min(),
data["GAL-LON"][masks[ell2]].max()),
fontsize = 14)
ax2.plot(np.degrees(np.arctan(xlim)),
np.log([0.1,0.1]), ls = ":", lw = 1,
color = "k", label = "0.1 R")
ax2.fill_between([-min_lat, min_lat]*u.deg, [ylim[0], ylim[0]], [ylim[1], ylim[1]],
color = pal[1],
alpha = 0.1,
label = r"$|b| < 5\degree$")
line_xx = np.linspace(y_min, y_max, 10)
line_yy_pos = siegel_result_pos[0] * line_xx + siegel_result_pos[1]
line_yy_neg = siegel_result_neg[0] * -line_xx + siegel_result_neg[1]
ax.plot(line_xx, line_yy_pos, color = "r", lw = 3, alpha = 0.9,
label = r"$H_{{n_e^2}} = {0:.2f} D$".format(1/-siegel_result_pos[0]))
ax.plot(-line_xx, line_yy_neg, color = "b", lw = 3, alpha = 0.9,
label = r"$H_{{n_e^2}} = {0:.2f} D$".format(1/siegel_result_neg[0]))
if deredden:
line_yy_pos_dr = siegel_result_pos_dr[0] * line_xx + siegel_result_pos_dr[1]
line_yy_neg_dr = siegel_result_neg_dr[0] * -line_xx + siegel_result_neg_dr[1]
ax.plot(line_xx, line_yy_pos_dr, color = "r", lw = 3, alpha = 0.9, ls = "--",
label = r"Dered: $H_{{n_e^2}} = {0:.2f} D$".format(1/-siegel_result_pos_dr[0]))
ax.plot(-line_xx, line_yy_neg_dr, color = "b", lw = 3, alpha = 0.9, ls = "--",
label = r"Dered: $H_{{n_e^2}} = {0:.2f} D$".format(1/siegel_result_neg_dr[0]))
ax.set_xlim(xlim)
ax.set_ylim(ylim)
ax2.set_xlabel(r"$b$ (deg)", fontsize = 12)
ax2.set_xlim(np.degrees(np.arctan(xlim)))
ax.legend(fontsize = 12, loc = 1)
ax2.legend(fontsize = 12, loc = 2)
plt.tight_layout()
plt.savefig(figure_name, dpi = 300)
del(fig)
plt.close()
results = {
"median_longitude":np.array(median_longitude),
"slopes_pos":np.array(slopes_pos),
"slopes_neg":np.array(slopes_neg),
"intercept_pos":np.array(intercept_pos),
"intercept_neg":np.array(intercept_neg)
}
if deredden:
results["median_distance"] = np.array(median_distance),
results["slopes_pos_dr"] = np.array(slopes_pos_dr)
results["slopes_neg_dr"] = np.array(slopes_neg_dr)
results["intercept_pos_dr"] = np.array(intercept_pos_dr)
results["intercept_neg_dr"] = np.array(intercept_neg_dr)
else:
yy_pos = yy[(xx > y_min) & (xx < y_max) & ~nan_mask]
xx_pos = xx[(xx > y_min) & (xx < y_max) & ~nan_mask]
yy_neg = yy[(xx < -y_min) & (xx > -y_max) & ~nan_mask]
xx_neg = xx[(xx < -y_min) & (xx > -y_max) & ~nan_mask]
if ((len(yy_pos) < 5) | (len(yy_neg) < 5)):
slopes_pos.append(np.mean(boot_pos[:,1], axis = 0))
slopes_neg.append(np.mean(boot_neg[:,1], axis = 0))
slopes_pos_err.append(np.std(boot_pos[:,1], axis = 0))
slopes_neg_err.append(np.std(boot_neg[:,1], axis = 0))
intercept_pos.append(np.mean(boot_pos[:,0], axis = 0))
intercept_neg.append(np.mean(boot_neg[:,0], axis = 0))
intercept_pos_err.append(np.std(boot_pos[:,0], axis = 0))
intercept_neg_err.append(np.std(boot_neg[:,0], axis = 0))
else:
if deredden:
zz_dr_pos = zz[(xx > y_min) & (xx < y_max) & ~nan_mask_z]
xx_dr_pos = xx[(xx > y_min) & (xx < y_max) & ~nan_mask_z]
zz_dr_neg = zz[(xx < -y_min) & (xx > -y_max) & ~nan_mask_z]
xx_dr_neg = xx[(xx < -y_min) & (xx > -y_max) & ~nan_mask_z]
def slope_int_estimator_pos_dr(inds,
YY = zz_dr_pos,
XX = xx_dr_pos):
"""
estimate slope using sm.RLM
"""
XX = XX[inds]
YY = YY[inds]
XX = sm.add_constant(XX)
res = sm.RLM(YY, XX, M=sm.robust.norms.HuberT()).fit()
return res.params
def slope_int_estimator_neg_dr(inds,
YY = zz_dr_neg,
XX = xx_dr_neg):
"""
estimate slope using sm.RLM
"""
XX = XX[inds]
YY = YY[inds]
XX = sm.add_constant(XX)
res = sm.RLM(YY, XX, M=sm.robust.norms.HuberT()).fit()
return res.params
def slope_int_estimator_pos(inds,
YY = yy_pos,
XX = xx_pos):
"""
estimate slope using sm.RLM
"""
XX = XX[inds]
YY = YY[inds]
XX = sm.add_constant(XX)
res = sm.RLM(YY, XX, M=sm.robust.norms.HuberT()).fit()
return res.params
def slope_int_estimator_neg(inds,
YY = yy_neg,
XX = xx_neg):
"""
estimate slope using sm.RLM
"""
XX = XX[inds]
YY = YY[inds]
XX = sm.add_constant(XX)
res = sm.RLM(YY, XX, M=sm.robust.norms.HuberT()).fit()
return res.params
boot_pos = bootstrap(np.arange(len(yy_pos)), func = slope_int_estimator_pos, n_boot = n_boot)
boot_neg = bootstrap(np.arange(len(yy_neg)), func = slope_int_estimator_neg, n_boot = n_boot)
slopes_pos.append(np.mean(boot_pos[:,1], axis = 0))
slopes_neg.append(np.mean(boot_neg[:,1], axis = 0))
slopes_pos_err.append(np.std(boot_pos[:,1], axis = 0))
slopes_neg_err.append(np.std(boot_neg[:,1], axis = 0))
intercept_pos.append(np.mean(boot_pos[:,0], axis = 0))
intercept_neg.append(np.mean(boot_neg[:,0], axis = 0))
intercept_pos_err.append(np.std(boot_pos[:,0], axis = 0))
intercept_neg_err.append(np.std(boot_neg[:,0], axis = 0))
if deredden:
boot_pos_dr = bootstrap(np.arange(len(zz_dr_pos)), func = slope_int_estimator_pos_dr, n_boot = n_boot)
boot_neg_dr = bootstrap(np.arange(len(zz_dr_neg)), func = slope_int_estimator_neg_dr, n_boot = n_boot)
slopes_pos_dr.append(np.mean(boot_pos_dr[:,1], axis = 0))
slopes_neg_dr.append(np.mean(boot_neg_dr[:,1], axis = 0))
slopes_pos_dr_err.append(np.std(boot_pos_dr[:,1], axis = 0))
slopes_neg_dr_err.append(np.std(boot_neg_dr[:,1], axis = 0))
intercept_pos_dr.append(np.mean(boot_pos_dr[:,0], axis = 0))
intercept_neg_dr.append(np.mean(boot_neg_dr[:,0], axis = 0))
intercept_pos_dr_err.append(np.std(boot_pos_dr[:,0], axis = 0))
intercept_neg_dr_err.append(np.std(boot_neg_dr[:,0], axis = 0))
if fig_names is not None:
figure_name = "{0}_{1}.png".format(fig_names, ell2)
if xlim is None:
xlim = np.array([-0.9, 0.9])
if ylim is None:
ylim = np.array([-4.6, 3.2])
fig = plt.figure()
ax = fig.add_subplot(111)
ax2 = ax.twiny()
ax.scatter(xx,
yy,
color ="k",
alpha = 0.8)
if deredden:
ax.scatter(xx,
zz,
color ="grey",
alpha = 0.8)
ax.set_xlabel(r"$\tan$(b)", fontsize= 12)
ax.set_ylabel(r"$\log$($H\alpha$ Intensity / R)", fontsize= 12)
ax.set_title(r"${0:.1f} < l < {1:.1f}$".format(data["GAL-LON"][masks[ell2]].min(),
data["GAL-LON"][masks[ell2]].max()),
fontsize = 14)
ax2.plot(np.degrees(np.arctan(xlim)),
np.log([0.1,0.1]), ls = ":", lw = 1,
color = "k", label = "0.1 R")
ax2.fill_between([-min_lat, min_lat]*u.deg, [ylim[0], ylim[0]], [ylim[1], ylim[1]],
color = pal[1],
alpha = 0.1,
label = r"$|b| < 5\degree$")
line_xx = np.linspace(y_min, y_max, 100)
def get_slope_conf_band(boot_res, X = line_xx):
yy = [[res[0] + res[1] * X] for res in boot_res]
yy = np.vstack(yy)
return np.percentile(yy, (5,95), axis = 0)
line_yy_pos = slopes_pos[-1] * line_xx + intercept_pos[-1]
line_yy_neg = slopes_neg[-1] * -line_xx + intercept_neg[-1]
line_yy_pos_range = get_slope_conf_band(boot_pos)
line_yy_neg_range = get_slope_conf_band(boot_neg, X = -line_xx)
ax.plot(line_xx, line_yy_pos, color = "r", lw = 3, alpha = 0.9,
label = r"$H_{{n_e^2}} = ({0:.2f} \pm {1:.2f}) D$".format(1/-slopes_pos[-1], np.abs(1/slopes_pos[-1] * slopes_pos_err[-1] / slopes_pos[-1])))
ax.fill_between(line_xx, line_yy_pos_range[0], line_yy_pos_range[1],
color = "r", alpha = 0.2)
ax.plot(-line_xx, line_yy_neg, color = "b", lw = 3, alpha = 0.9,
label = r"$H_{{n_e^2}} = ({0:.2f} \pm {1:.2f}) D$".format(1/slopes_neg[-1], np.abs(-1/slopes_pos[-1] * slopes_pos_err[-1] / slopes_pos[-1])))
ax.fill_between(-line_xx, line_yy_neg_range[0], line_yy_neg_range[1],
color = "b", alpha = 0.2)
if deredden:
line_yy_pos_dr = slopes_pos_dr[-1] * line_xx + intercept_pos_dr[-1]
line_yy_neg_dr = slopes_neg_dr[-1] * -line_xx + intercept_neg_dr[-1]
line_yy_pos_range_dr = get_slope_conf_band(boot_pos_dr)
line_yy_neg_range_dr = get_slope_conf_band(boot_neg_dr, X = -line_xx)
ax.plot(line_xx, line_yy_pos_dr, color = "r", lw = 3, alpha = 0.9, ls = "--",
label = r"Dered: $H_{{n_e^2}} = ({0:.2f} \pm {1:.2f}) D$".format(1/-slopes_pos_dr[-1], np.abs(1/slopes_pos_dr[-1] * slopes_pos_dr_err[-1] / slopes_pos_dr[-1])))
ax.fill_between(line_xx, line_yy_pos_range_dr[0], line_yy_pos_range_dr[1],
color = "r", alpha = 0.2)
ax.plot(-line_xx, line_yy_neg_dr, color = "b", lw = 3, alpha = 0.9, ls = "--",
label = r"Dered: $H_{{n_e^2}} = ({0:.2f} \pm {1:.2f}) D$".format(1/slopes_neg_dr[-1], np.abs(-1/slopes_pos_dr[-1] * slopes_pos_dr_err[-1] / slopes_pos_dr[-1])))
ax.fill_between(-line_xx, line_yy_neg_range_dr[0], line_yy_neg_range_dr[1],
color = "b", alpha = 0.2)
ax.set_xlim(xlim)
ax.set_ylim(ylim)
ax2.set_xlabel(r"$b$ (deg)", fontsize = 12)
ax2.set_xlim(np.degrees(np.arctan(xlim)))
ax.legend(fontsize = 12, loc = 1)
ax2.legend(fontsize = 12, loc = 2)
plt.tight_layout()
plt.savefig(figure_name, dpi = 300)
del(fig)
plt.close()
results = {
"median_longitude":np.array(median_longitude),
"slopes_pos":np.array(slopes_pos),
"slopes_neg":np.array(slopes_neg),
"intercept_pos":np.array(intercept_pos),
"intercept_neg":np.array(intercept_neg),
"slopes_pos_err":np.array(slopes_pos_err),
"slopes_neg_err":np.array(slopes_neg_err),
"intercept_pos_err":np.array(intercept_pos_err),
"intercept_neg_err":np.array(intercept_neg_err)
}
if deredden:
results["median_distance"] = np.array(median_distance),
results["slopes_pos_dr"] = np.array(slopes_pos_dr)
results["slopes_neg_dr"] = np.array(slopes_neg_dr)
results["intercept_pos_dr"] = np.array(intercept_pos_dr)
results["intercept_neg_dr"] = np.array(intercept_neg_dr)
results["slopes_pos_dr_err"] = np.array(slopes_pos_dr_err)
results["slopes_neg_dr_err"] = np.array(slopes_neg_dr_err)
results["intercept_pos_dr_err"] = np.array(intercept_pos_dr_err)
results["intercept_neg_dr_err"] = np.array(intercept_neg_dr_err)
if return_smoothed:
results["smoothed_longitude"] = np.arange(np.min(median_longitude),
np.max(median_longitude), 0.25)
if deredden:
distance_interp = interp1d(median_longitude, median_distance)
results["smoothed_distance"] = distance_interp(results["smoothed_longitude"])
smoothed_slope_pos_ha = np.zeros((3,len(results["smoothed_longitude"])))
smoothed_slope_neg_ha = np.zeros((3,len(results["smoothed_longitude"])))
smoothed_slope_pos_ha_dr = np.zeros((3,len(results["smoothed_longitude"])))
smoothed_slope_neg_ha_dr = np.zeros((3,len(results["smoothed_longitude"])))
for ell,lon in enumerate(results["smoothed_longitude"]):
smoothed_slope_pos_ha[:,ell] = np.nanpercentile(np.array(slopes_pos)[(median_longitude <= lon + smoothed_width.value/2) &
(median_longitude > lon - smoothed_width.value/2)],
(10, 50, 90))
smoothed_slope_neg_ha[:,ell] = np.nanpercentile(np.array(slopes_neg)[(median_longitude <= lon + smoothed_width.value/2) &
(median_longitude > lon - smoothed_width.value/2)],
(10, 50, 90))
if deredden:
smoothed_slope_pos_ha_dr[:,ell] = np.nanpercentile(np.array(slopes_pos_dr)[(median_longitude <= lon + smoothed_width.value/2) &
(median_longitude > lon - smoothed_width.value/2)],
(10, 50, 90))
smoothed_slope_neg_ha_dr[:,ell] = np.nanpercentile(np.array(slopes_neg_dr)[(median_longitude <= lon + smoothed_width.value/2) &
(median_longitude > lon - smoothed_width.value/2)],
(10, 50, 90))
results["smoothed_slopes_pos"] = smoothed_slope_pos_ha
results["smoothed_slopes_neg"] = smoothed_slope_neg_ha
if deredden:
results["smoothed_slopes_pos_dr"] = smoothed_slope_pos_ha_dr
results["smoothed_slopes_neg_dr"] = smoothed_slope_neg_ha_dr
return results
| [
"numpy.abs",
"numpy.isnan",
"matplotlib.pyplot.figure",
"numpy.sin",
"numpy.mean",
"scipy.interpolate.interp1d",
"astropy.coordinates.Angle",
"matplotlib.pyplot.tight_layout",
"numpy.round",
"statsmodels.api.robust.norms.HuberT",
"logging.warning",
"matplotlib.pyplot.close",
"numpy.std",
"... | [((723, 754), 'seaborn.color_palette', 'sns.color_palette', (['"""colorblind"""'], {}), "('colorblind')\n", (740, 754), True, 'import seaborn as sns\n'), ((5206, 5242), 'numpy.tan', 'np.tan', (["(data['GAL-LAT'].data * u.deg)"], {}), "(data['GAL-LAT'].data * u.deg)\n", (5212, 5242), True, 'import numpy as np\n'), ((920, 937), 'numpy.cos', 'np.cos', (['(l * u.deg)'], {}), '(l * u.deg)\n', (926, 937), True, 'import numpy as np\n'), ((3524, 3554), 'numpy.all', 'np.all', (["kwargs['return_track']"], {}), "(kwargs['return_track'])\n", (3530, 3554), True, 'import numpy as np\n'), ((7746, 7794), 'numpy.linspace', 'np.linspace', (['lon_range[0]', 'lon_range[1]', 'n_steps'], {}), '(lon_range[0], lon_range[1], n_steps)\n', (7757, 7794), True, 'import numpy as np\n'), ((11203, 11237), 'numpy.log', 'np.log', (["data['INTEN'][masks[ell2]]"], {}), "(data['INTEN'][masks[ell2]])\n", (11209, 11237), True, 'import numpy as np\n'), ((11257, 11269), 'numpy.isnan', 'np.isnan', (['yy'], {}), '(yy)\n', (11265, 11269), True, 'import numpy as np\n'), ((11290, 11302), 'numpy.isinf', 'np.isinf', (['yy'], {}), '(yy)\n', (11298, 11302), True, 'import numpy as np\n'), ((11657, 11672), 'numpy.tan', 'np.tan', (['min_lat'], {}), '(min_lat)\n', (11663, 11672), True, 'import numpy as np\n'), ((11689, 11704), 'numpy.tan', 'np.tan', (['max_lat'], {}), '(max_lat)\n', (11695, 11704), True, 'import numpy as np\n'), ((3726, 3788), 'logging.warning', 'logging.warning', (['"""keyword \'return_track\' must be set to True!"""'], {}), '("keyword \'return_track\' must be set to True!")\n', (3741, 3788), False, 'import logging\n'), ((4939, 4954), 'dustmaps.marshall.MarshallQuery', 'MarshallQuery', ([], {}), '()\n', (4952, 4954), False, 'from dustmaps.marshall import MarshallQuery\n'), ((5887, 5905), 'numpy.array', 'np.array', (['[6562.8]'], {}), '([6562.8])\n', (5895, 5905), True, 'import numpy as np\n'), ((5932, 5960), 'extinction.fm07', 'extinction_law', (['wave_ha', '(1.0)'], {}), '(wave_ha, 1.0)\n', (5946, 5960), True, 'from extinction import fm07 as extinction_law\n'), ((6574, 6592), 'numpy.array', 'np.array', (['[6562.8]'], {}), '([6562.8])\n', (6582, 6592), True, 'import numpy as np\n'), ((6619, 6647), 'extinction.fm07', 'extinction_law', (['wave_ha', '(1.0)'], {}), '(wave_ha, 1.0)\n', (6633, 6647), True, 'from extinction import fm07 as extinction_law\n'), ((7173, 7251), 'logging.warning', 'logging.warning', (['"""No units provided for longitude_mask_width, assuming u.deg."""'], {}), "('No units provided for longitude_mask_width, assuming u.deg.')\n", (7188, 7251), False, 'import logging\n'), ((7604, 7623), 'numpy.min', 'np.min', (['wrapped_lon'], {}), '(wrapped_lon)\n', (7610, 7623), True, 'import numpy as np\n'), ((7625, 7644), 'numpy.max', 'np.max', (['wrapped_lon'], {}), '(wrapped_lon)\n', (7631, 7644), True, 'import numpy as np\n'), ((11350, 11390), 'numpy.log', 'np.log', (["data['INTEN_DERED'][masks[ell2]]"], {}), "(data['INTEN_DERED'][masks[ell2]])\n", (11356, 11390), True, 'import numpy as np\n'), ((11416, 11428), 'numpy.isnan', 'np.isnan', (['zz'], {}), '(zz)\n', (11424, 11428), True, 'import numpy as np\n'), ((11455, 11467), 'numpy.isinf', 'np.isinf', (['zz'], {}), '(zz)\n', (11463, 11467), True, 'import numpy as np\n'), ((11501, 11540), 'numpy.median', 'np.median', (["data['GAL-LON'][masks[ell2]]"], {}), "(data['GAL-LON'][masks[ell2]])\n", (11510, 11540), True, 'import numpy as np\n'), ((28437, 28461), 'numpy.min', 'np.min', (['median_longitude'], {}), '(median_longitude)\n', (28443, 28461), True, 'import numpy as np\n'), ((28476, 28500), 'numpy.max', 'np.max', (['median_longitude'], {}), '(median_longitude)\n', (28482, 28500), True, 'import numpy as np\n'), ((28559, 28602), 'scipy.interpolate.interp1d', 'interp1d', (['median_longitude', 'median_distance'], {}), '(median_longitude, median_distance)\n', (28567, 28602), False, 'from scipy.interpolate import interp1d\n'), ((952, 969), 'numpy.sin', 'np.sin', (['(l * u.deg)'], {}), '(l * u.deg)\n', (958, 969), True, 'import numpy as np\n'), ((1000, 1017), 'numpy.sin', 'np.sin', (['(l * u.deg)'], {}), '(l * u.deg)\n', (1006, 1017), True, 'import numpy as np\n'), ((7427, 7494), 'logging.warning', 'logging.warning', (['"""No units provided for step_size, assuming u.deg."""'], {}), "('No units provided for step_size, assuming u.deg.')\n", (7442, 7494), False, 'import logging\n'), ((7544, 7566), 'astropy.coordinates.Angle', 'Angle', (["data['GAL-LON']"], {}), "(data['GAL-LON'])\n", (7549, 7566), False, 'from astropy.coordinates import Angle\n'), ((11598, 11638), 'numpy.median', 'np.median', (["data['DISTANCE'][masks[ell2]]"], {}), "(data['DISTANCE'][masks[ell2]])\n", (11607, 11638), True, 'import numpy as np\n'), ((11872, 11981), 'logging.warning', 'logging.warning', (['"""Installed version of scipy does not have the siegelslopes method in scipy.stats!"""'], {}), "(\n 'Installed version of scipy does not have the siegelslopes method in scipy.stats!'\n )\n", (11887, 11981), False, 'import logging\n'), ((13660, 13672), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (13670, 13672), True, 'import matplotlib.pyplot as plt\n'), ((14928, 14957), 'numpy.linspace', 'np.linspace', (['y_min', 'y_max', '(10)'], {}), '(y_min, y_max, 10)\n', (14939, 14957), True, 'import numpy as np\n'), ((16476, 16494), 'matplotlib.pyplot.tight_layout', 'plt.tight_layout', ([], {}), '()\n', (16492, 16494), True, 'import matplotlib.pyplot as plt\n'), ((16512, 16545), 'matplotlib.pyplot.savefig', 'plt.savefig', (['figure_name'], {'dpi': '(300)'}), '(figure_name, dpi=300)\n', (16523, 16545), True, 'import matplotlib.pyplot as plt\n'), ((16589, 16600), 'matplotlib.pyplot.close', 'plt.close', ([], {}), '()\n', (16598, 16600), True, 'import matplotlib.pyplot as plt\n'), ((16657, 16683), 'numpy.array', 'np.array', (['median_longitude'], {}), '(median_longitude)\n', (16665, 16683), True, 'import numpy as np\n'), ((16710, 16730), 'numpy.array', 'np.array', (['slopes_pos'], {}), '(slopes_pos)\n', (16718, 16730), True, 'import numpy as np\n'), ((16757, 16777), 'numpy.array', 'np.array', (['slopes_neg'], {}), '(slopes_neg)\n', (16765, 16777), True, 'import numpy as np\n'), ((16807, 16830), 'numpy.array', 'np.array', (['intercept_pos'], {}), '(intercept_pos)\n', (16815, 16830), True, 'import numpy as np\n'), ((16860, 16883), 'numpy.array', 'np.array', (['intercept_neg'], {}), '(intercept_neg)\n', (16868, 16883), True, 'import numpy as np\n'), ((17040, 17063), 'numpy.array', 'np.array', (['slopes_pos_dr'], {}), '(slopes_pos_dr)\n', (17048, 17063), True, 'import numpy as np\n'), ((17107, 17130), 'numpy.array', 'np.array', (['slopes_neg_dr'], {}), '(slopes_neg_dr)\n', (17115, 17130), True, 'import numpy as np\n'), ((17177, 17203), 'numpy.array', 'np.array', (['intercept_pos_dr'], {}), '(intercept_pos_dr)\n', (17185, 17203), True, 'import numpy as np\n'), ((17250, 17276), 'numpy.array', 'np.array', (['intercept_neg_dr'], {}), '(intercept_neg_dr)\n', (17258, 17276), True, 'import numpy as np\n'), ((27198, 27224), 'numpy.array', 'np.array', (['median_longitude'], {}), '(median_longitude)\n', (27206, 27224), True, 'import numpy as np\n'), ((27251, 27271), 'numpy.array', 'np.array', (['slopes_pos'], {}), '(slopes_pos)\n', (27259, 27271), True, 'import numpy as np\n'), ((27298, 27318), 'numpy.array', 'np.array', (['slopes_neg'], {}), '(slopes_neg)\n', (27306, 27318), True, 'import numpy as np\n'), ((27348, 27371), 'numpy.array', 'np.array', (['intercept_pos'], {}), '(intercept_pos)\n', (27356, 27371), True, 'import numpy as np\n'), ((27401, 27424), 'numpy.array', 'np.array', (['intercept_neg'], {}), '(intercept_neg)\n', (27409, 27424), True, 'import numpy as np\n'), ((27455, 27479), 'numpy.array', 'np.array', (['slopes_pos_err'], {}), '(slopes_pos_err)\n', (27463, 27479), True, 'import numpy as np\n'), ((27510, 27534), 'numpy.array', 'np.array', (['slopes_neg_err'], {}), '(slopes_neg_err)\n', (27518, 27534), True, 'import numpy as np\n'), ((27568, 27595), 'numpy.array', 'np.array', (['intercept_pos_err'], {}), '(intercept_pos_err)\n', (27576, 27595), True, 'import numpy as np\n'), ((27629, 27656), 'numpy.array', 'np.array', (['intercept_neg_err'], {}), '(intercept_neg_err)\n', (27637, 27656), True, 'import numpy as np\n'), ((27813, 27836), 'numpy.array', 'np.array', (['slopes_pos_dr'], {}), '(slopes_pos_dr)\n', (27821, 27836), True, 'import numpy as np\n'), ((27880, 27903), 'numpy.array', 'np.array', (['slopes_neg_dr'], {}), '(slopes_neg_dr)\n', (27888, 27903), True, 'import numpy as np\n'), ((27950, 27976), 'numpy.array', 'np.array', (['intercept_pos_dr'], {}), '(intercept_pos_dr)\n', (27958, 27976), True, 'import numpy as np\n'), ((28023, 28049), 'numpy.array', 'np.array', (['intercept_neg_dr'], {}), '(intercept_neg_dr)\n', (28031, 28049), True, 'import numpy as np\n'), ((28097, 28124), 'numpy.array', 'np.array', (['slopes_pos_dr_err'], {}), '(slopes_pos_dr_err)\n', (28105, 28124), True, 'import numpy as np\n'), ((28172, 28199), 'numpy.array', 'np.array', (['slopes_neg_dr_err'], {}), '(slopes_neg_dr_err)\n', (28180, 28199), True, 'import numpy as np\n'), ((28250, 28280), 'numpy.array', 'np.array', (['intercept_pos_dr_err'], {}), '(intercept_pos_dr_err)\n', (28258, 28280), True, 'import numpy as np\n'), ((28331, 28361), 'numpy.array', 'np.array', (['intercept_neg_dr_err'], {}), '(intercept_neg_dr_err)\n', (28339, 28361), True, 'import numpy as np\n'), ((1054, 1071), 'numpy.sin', 'np.sin', (['(l * u.deg)'], {}), '(l * u.deg)\n', (1060, 1071), True, 'import numpy as np\n'), ((5415, 5454), 'astropy.coordinates.Angle', 'Angle', (['(data.lbv_RBD_track[:, 0] * u.deg)'], {}), '(data.lbv_RBD_track[:, 0] * u.deg)\n', (5420, 5454), False, 'from astropy.coordinates import Angle\n'), ((5592, 5627), 'astropy.coordinates.Angle', 'Angle', (["(data['GAL-LON'].data * u.deg)"], {}), "(data['GAL-LON'].data * u.deg)\n", (5597, 5627), False, 'from astropy.coordinates import Angle\n'), ((6188, 6209), 'numpy.isnan', 'np.isnan', (['Av_bayestar'], {}), '(Av_bayestar)\n', (6196, 6209), True, 'import numpy as np\n'), ((6881, 6894), 'numpy.isnan', 'np.isnan', (['AKs'], {}), '(AKs)\n', (6889, 6894), True, 'import numpy as np\n'), ((7675, 7712), 'numpy.round', 'np.round', (['(lon_range[1] - lon_range[0])'], {}), '(lon_range[1] - lon_range[0])\n', (7683, 7712), True, 'import numpy as np\n'), ((13533, 13554), 'numpy.array', 'np.array', (['[-0.9, 0.9]'], {}), '([-0.9, 0.9])\n', (13541, 13554), True, 'import numpy as np\n'), ((13615, 13636), 'numpy.array', 'np.array', (['[-4.6, 3.2]'], {}), '([-4.6, 3.2])\n', (13623, 13636), True, 'import numpy as np\n'), ((14553, 14571), 'numpy.log', 'np.log', (['[0.1, 0.1]'], {}), '([0.1, 0.1])\n', (14559, 14571), True, 'import numpy as np\n'), ((16970, 16995), 'numpy.array', 'np.array', (['median_distance'], {}), '(median_distance)\n', (16978, 16995), True, 'import numpy as np\n'), ((17646, 17677), 'numpy.mean', 'np.mean', (['boot_pos[:, 1]'], {'axis': '(0)'}), '(boot_pos[:, 1], axis=0)\n', (17653, 17677), True, 'import numpy as np\n'), ((17714, 17745), 'numpy.mean', 'np.mean', (['boot_neg[:, 1]'], {'axis': '(0)'}), '(boot_neg[:, 1], axis=0)\n', (17721, 17745), True, 'import numpy as np\n'), ((17786, 17816), 'numpy.std', 'np.std', (['boot_pos[:, 1]'], {'axis': '(0)'}), '(boot_pos[:, 1], axis=0)\n', (17792, 17816), True, 'import numpy as np\n'), ((17857, 17887), 'numpy.std', 'np.std', (['boot_neg[:, 1]'], {'axis': '(0)'}), '(boot_neg[:, 1], axis=0)\n', (17863, 17887), True, 'import numpy as np\n'), ((17944, 17975), 'numpy.mean', 'np.mean', (['boot_pos[:, 0]'], {'axis': '(0)'}), '(boot_pos[:, 0], axis=0)\n', (17951, 17975), True, 'import numpy as np\n'), ((18015, 18046), 'numpy.mean', 'np.mean', (['boot_neg[:, 0]'], {'axis': '(0)'}), '(boot_neg[:, 0], axis=0)\n', (18022, 18046), True, 'import numpy as np\n'), ((18090, 18120), 'numpy.std', 'np.std', (['boot_pos[:, 0]'], {'axis': '(0)'}), '(boot_pos[:, 0], axis=0)\n', (18096, 18120), True, 'import numpy as np\n'), ((18164, 18194), 'numpy.std', 'np.std', (['boot_neg[:, 0]'], {'axis': '(0)'}), '(boot_neg[:, 0], axis=0)\n', (18170, 18194), True, 'import numpy as np\n'), ((19855, 19874), 'statsmodels.api.add_constant', 'sm.add_constant', (['XX'], {}), '(XX)\n', (19870, 19874), True, 'import statsmodels.api as sm\n'), ((20296, 20315), 'statsmodels.api.add_constant', 'sm.add_constant', (['XX'], {}), '(XX)\n', (20311, 20315), True, 'import statsmodels.api as sm\n'), ((20702, 20733), 'numpy.mean', 'np.mean', (['boot_pos[:, 1]'], {'axis': '(0)'}), '(boot_pos[:, 1], axis=0)\n', (20709, 20733), True, 'import numpy as np\n'), ((20770, 20801), 'numpy.mean', 'np.mean', (['boot_neg[:, 1]'], {'axis': '(0)'}), '(boot_neg[:, 1], axis=0)\n', (20777, 20801), True, 'import numpy as np\n'), ((20842, 20872), 'numpy.std', 'np.std', (['boot_pos[:, 1]'], {'axis': '(0)'}), '(boot_pos[:, 1], axis=0)\n', (20848, 20872), True, 'import numpy as np\n'), ((20913, 20943), 'numpy.std', 'np.std', (['boot_neg[:, 1]'], {'axis': '(0)'}), '(boot_neg[:, 1], axis=0)\n', (20919, 20943), True, 'import numpy as np\n'), ((21000, 21031), 'numpy.mean', 'np.mean', (['boot_pos[:, 0]'], {'axis': '(0)'}), '(boot_pos[:, 0], axis=0)\n', (21007, 21031), True, 'import numpy as np\n'), ((21071, 21102), 'numpy.mean', 'np.mean', (['boot_neg[:, 0]'], {'axis': '(0)'}), '(boot_neg[:, 0], axis=0)\n', (21078, 21102), True, 'import numpy as np\n'), ((21146, 21176), 'numpy.std', 'np.std', (['boot_pos[:, 0]'], {'axis': '(0)'}), '(boot_pos[:, 0], axis=0)\n', (21152, 21176), True, 'import numpy as np\n'), ((21220, 21250), 'numpy.std', 'np.std', (['boot_neg[:, 0]'], {'axis': '(0)'}), '(boot_neg[:, 0], axis=0)\n', (21226, 21250), True, 'import numpy as np\n'), ((22523, 22535), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (22533, 22535), True, 'import matplotlib.pyplot as plt\n'), ((23887, 23917), 'numpy.linspace', 'np.linspace', (['y_min', 'y_max', '(100)'], {}), '(y_min, y_max, 100)\n', (23898, 23917), True, 'import numpy as np\n'), ((26996, 27014), 'matplotlib.pyplot.tight_layout', 'plt.tight_layout', ([], {}), '()\n', (27012, 27014), True, 'import matplotlib.pyplot as plt\n'), ((27036, 27069), 'matplotlib.pyplot.savefig', 'plt.savefig', (['figure_name'], {'dpi': '(300)'}), '(figure_name, dpi=300)\n', (27047, 27069), True, 'import matplotlib.pyplot as plt\n'), ((27121, 27132), 'matplotlib.pyplot.close', 'plt.close', ([], {}), '()\n', (27130, 27132), True, 'import matplotlib.pyplot as plt\n'), ((27743, 27768), 'numpy.array', 'np.array', (['median_distance'], {}), '(median_distance)\n', (27751, 27768), True, 'import numpy as np\n'), ((29148, 29168), 'numpy.array', 'np.array', (['slopes_pos'], {}), '(slopes_pos)\n', (29156, 29168), True, 'import numpy as np\n'), ((29458, 29478), 'numpy.array', 'np.array', (['slopes_neg'], {}), '(slopes_neg)\n', (29466, 29478), True, 'import numpy as np\n'), ((6250, 6271), 'numpy.isnan', 'np.isnan', (['Av_bayestar'], {}), '(Av_bayestar)\n', (6258, 6271), True, 'import numpy as np\n'), ((6935, 6948), 'numpy.isnan', 'np.isnan', (['AKs'], {}), '(AKs)\n', (6943, 6948), True, 'import numpy as np\n'), ((14509, 14524), 'numpy.arctan', 'np.arctan', (['xlim'], {}), '(xlim)\n', (14518, 14524), True, 'import numpy as np\n'), ((16339, 16354), 'numpy.arctan', 'np.arctan', (['xlim'], {}), '(xlim)\n', (16348, 16354), True, 'import numpy as np\n'), ((18912, 18931), 'statsmodels.api.add_constant', 'sm.add_constant', (['XX'], {}), '(XX)\n', (18927, 18931), True, 'import statsmodels.api as sm\n'), ((19406, 19425), 'statsmodels.api.add_constant', 'sm.add_constant', (['XX'], {}), '(XX)\n', (19421, 19425), True, 'import statsmodels.api as sm\n'), ((21571, 21605), 'numpy.mean', 'np.mean', (['boot_pos_dr[:, 1]'], {'axis': '(0)'}), '(boot_pos_dr[:, 1], axis=0)\n', (21578, 21605), True, 'import numpy as np\n'), ((21649, 21683), 'numpy.mean', 'np.mean', (['boot_neg_dr[:, 1]'], {'axis': '(0)'}), '(boot_neg_dr[:, 1], axis=0)\n', (21656, 21683), True, 'import numpy as np\n'), ((21731, 21764), 'numpy.std', 'np.std', (['boot_pos_dr[:, 1]'], {'axis': '(0)'}), '(boot_pos_dr[:, 1], axis=0)\n', (21737, 21764), True, 'import numpy as np\n'), ((21812, 21845), 'numpy.std', 'np.std', (['boot_neg_dr[:, 1]'], {'axis': '(0)'}), '(boot_neg_dr[:, 1], axis=0)\n', (21818, 21845), True, 'import numpy as np\n'), ((21913, 21947), 'numpy.mean', 'np.mean', (['boot_pos_dr[:, 0]'], {'axis': '(0)'}), '(boot_pos_dr[:, 0], axis=0)\n', (21920, 21947), True, 'import numpy as np\n'), ((21994, 22028), 'numpy.mean', 'np.mean', (['boot_neg_dr[:, 0]'], {'axis': '(0)'}), '(boot_neg_dr[:, 0], axis=0)\n', (22001, 22028), True, 'import numpy as np\n'), ((22079, 22112), 'numpy.std', 'np.std', (['boot_pos_dr[:, 0]'], {'axis': '(0)'}), '(boot_pos_dr[:, 0], axis=0)\n', (22085, 22112), True, 'import numpy as np\n'), ((22163, 22196), 'numpy.std', 'np.std', (['boot_neg_dr[:, 0]'], {'axis': '(0)'}), '(boot_neg_dr[:, 0], axis=0)\n', (22169, 22196), True, 'import numpy as np\n'), ((22384, 22405), 'numpy.array', 'np.array', (['[-0.9, 0.9]'], {}), '([-0.9, 0.9])\n', (22392, 22405), True, 'import numpy as np\n'), ((22474, 22495), 'numpy.array', 'np.array', (['[-4.6, 3.2]'], {}), '([-4.6, 3.2])\n', (22482, 22495), True, 'import numpy as np\n'), ((23488, 23506), 'numpy.log', 'np.log', (['[0.1, 0.1]'], {}), '([0.1, 0.1])\n', (23494, 23506), True, 'import numpy as np\n'), ((24088, 24101), 'numpy.vstack', 'np.vstack', (['yy'], {}), '(yy)\n', (24097, 24101), True, 'import numpy as np\n'), ((24133, 24167), 'numpy.percentile', 'np.percentile', (['yy', '(5, 95)'], {'axis': '(0)'}), '(yy, (5, 95), axis=0)\n', (24146, 24167), True, 'import numpy as np\n'), ((29800, 29823), 'numpy.array', 'np.array', (['slopes_pos_dr'], {}), '(slopes_pos_dr)\n', (29808, 29823), True, 'import numpy as np\n'), ((30128, 30151), 'numpy.array', 'np.array', (['slopes_neg_dr'], {}), '(slopes_neg_dr)\n', (30136, 30151), True, 'import numpy as np\n'), ((23440, 23455), 'numpy.arctan', 'np.arctan', (['xlim'], {}), '(xlim)\n', (23449, 23455), True, 'import numpy as np\n'), ((26847, 26862), 'numpy.arctan', 'np.arctan', (['xlim'], {}), '(xlim)\n', (26856, 26862), True, 'import numpy as np\n'), ((6314, 6335), 'numpy.isnan', 'np.isnan', (['Av_bayestar'], {}), '(Av_bayestar)\n', (6322, 6335), True, 'import numpy as np\n'), ((6996, 7009), 'numpy.isnan', 'np.isnan', (['AKs'], {}), '(AKs)\n', (7004, 7009), True, 'import numpy as np\n'), ((24675, 24739), 'numpy.abs', 'np.abs', (['(1 / slopes_pos[-1] * slopes_pos_err[-1] / slopes_pos[-1])'], {}), '(1 / slopes_pos[-1] * slopes_pos_err[-1] / slopes_pos[-1])\n', (24681, 24739), True, 'import numpy as np\n'), ((25071, 25136), 'numpy.abs', 'np.abs', (['(-1 / slopes_pos[-1] * slopes_pos_err[-1] / slopes_pos[-1])'], {}), '(-1 / slopes_pos[-1] * slopes_pos_err[-1] / slopes_pos[-1])\n', (25077, 25136), True, 'import numpy as np\n'), ((19918, 19942), 'statsmodels.api.robust.norms.HuberT', 'sm.robust.norms.HuberT', ([], {}), '()\n', (19940, 19942), True, 'import statsmodels.api as sm\n'), ((20359, 20383), 'statsmodels.api.robust.norms.HuberT', 'sm.robust.norms.HuberT', ([], {}), '()\n', (20381, 20383), True, 'import statsmodels.api as sm\n'), ((25893, 25966), 'numpy.abs', 'np.abs', (['(1 / slopes_pos_dr[-1] * slopes_pos_dr_err[-1] / slopes_pos_dr[-1])'], {}), '(1 / slopes_pos_dr[-1] * slopes_pos_dr_err[-1] / slopes_pos_dr[-1])\n', (25899, 25966), True, 'import numpy as np\n'), ((26342, 26416), 'numpy.abs', 'np.abs', (['(-1 / slopes_pos_dr[-1] * slopes_pos_dr_err[-1] / slopes_pos_dr[-1])'], {}), '(-1 / slopes_pos_dr[-1] * slopes_pos_dr_err[-1] / slopes_pos_dr[-1])\n', (26348, 26416), True, 'import numpy as np\n'), ((18979, 19003), 'statsmodels.api.robust.norms.HuberT', 'sm.robust.norms.HuberT', ([], {}), '()\n', (19001, 19003), True, 'import statsmodels.api as sm\n'), ((19473, 19497), 'statsmodels.api.robust.norms.HuberT', 'sm.robust.norms.HuberT', ([], {}), '()\n', (19495, 19497), True, 'import statsmodels.api as sm\n')] |
"""EmukitDesigner wraps emukit into Vizier Designer."""
import enum
from typing import Optional, Sequence
from absl import logging
from emukit import core
from emukit import model_wrappers
from emukit.bayesian_optimization import acquisitions
from emukit.bayesian_optimization import loops
from emukit.core import initial_designs
from GPy import kern
from GPy import models
from GPy.core.parameterization import priors
from GPy.util import linalg
import numpy as np
from vizier import algorithms as vza
from vizier import pyvizier as vz
from vizier.pyvizier import converters
RandomDesign = initial_designs.RandomDesign
def _create_constrained_gp(features: np.ndarray, labels: np.ndarray):
"""Creates a constraint gp."""
# This logging is too chatty because paramz transformations do not implement
# log jacobians. Silence it.
logging.logging.getLogger('paramz.transformations').setLevel(
logging.logging.CRITICAL)
class LogGaussian:
"""Multi-variate version of Loggaussian.
GPy surprisingly doesn't have this. The expected API of lnpdf and lnpdf_grad
are not precisely defined, so this handwaves a lot of stuff based on how
MultiVariateGaussian is implemented.
"""
domain = 'positive'
def __init__(self, mu, sigma):
self.mu = (mu)
self.sigma = (sigma)
self.inv, _, self.hld, _ = linalg.pdinv(self.sigma)
self.sigma2 = np.square(self.sigma)
self.constant = -0.5 * (self.mu.size * np.log(2 * np.pi) + self.hld)
def lnpdf(self, x):
x = np.array(x).flatten()
d = np.log(x) - self.mu
# Constant is dropped. Exact value doesn't really matter. Hopefully.
return -0.5 * np.dot(d.T, np.dot(self.inv, d))
def lnpdf_grad(self, x):
x = np.array(x).flatten()
d = np.log(x) - self.mu
return -np.dot(self.inv, d)
def rvs(self, n):
return np.exp(
np.random.randn(int(n), self.sigma.shape[0]) * self.sigma + self.mu)
# Use heavy tailed priors, but start with small values.
kernel = kern.Matern52(features.shape[1], variance=.04, ARD=True)
kernel.unconstrain()
loggaussian = LogGaussian(
np.zeros(features.shape[1:]),
sigma=np.diag(np.ones(features.shape[1:]) * 4.6))
kernel.lengthscale.set_prior(loggaussian)
kernel.lengthscale.constrain_bounded(1e-2, 1e2)
kernel.variance.set_prior(priors.LogGaussian(-3.2, 4.6))
kernel.variance.constrain_bounded(1e-3, 1e1)
gpy_model = models.GPRegression(features, labels, kernel, noise_var=0.0039)
gpy_model.likelihood.unconstrain()
gpy_model.likelihood.variance.set_prior(priors.LogGaussian(-5.5, sigma=4.6))
gpy_model.likelihood.variance.constrain_bounded(1e-10, 1.)
gpy_model.optimize_restarts(20, robust=True, optimizer='lbfgsb')
logging.info('After train: %s, %s', gpy_model, gpy_model.kern.lengthscale)
return gpy_model
def _to_emukit_parameter(spec: converters.NumpyArraySpec) -> core.Parameter:
if spec.type == converters.NumpyArraySpecType.ONEHOT_EMBEDDING:
return core.CategoricalParameter(
spec.name,
core.OneHotEncoding(list(range(spec.num_dimensions - spec.num_oovs))))
elif spec.type == converters.NumpyArraySpecType.CONTINUOUS:
return core.ContinuousParameter(spec.name, spec.bounds[0], spec.bounds[1])
else:
raise ValueError(f'Unknown type: {spec.type.name} in {spec}')
def _to_emukit_parameters(search_space: vz.SearchSpace) -> core.ParameterSpace:
parameters = [_to_emukit_parameter(pc) for pc in search_space.parameters]
return core.ParameterSpace(parameters)
class Version(enum.Enum):
DEFAULT_EI = 'emukit_default_ei'
MATERN52_UCB = 'emukit_matern52_ucb_ard'
class EmukitDesigner(vza.Designer):
"""Wraps emukit library as a Vizier designer."""
def __init__(self,
study_config: vz.StudyConfig,
*,
version: Version = Version.DEFAULT_EI,
num_random_samples: int = 10,
metadata_ns: str = 'emukit'):
"""Init.
Args:
study_config: Must be a flat study with a single metric.
version: Determines the behavior. See Version.
num_random_samples: This designer suggests random points until this many
trials have been observed.
metadata_ns: Metadata namespace that this designer writes to.
Raises:
ValueError:
"""
if study_config.search_space.is_conditional:
raise ValueError(f'{type(self)} does not support conditional search.')
if len(study_config.metric_information) != 1:
raise ValueError(f'{type(self)} works with exactly one metric.')
self._study_config = study_config
self._version = Version(version)
# Emukit pipeline's model and acquisition optimizer use the same
# representation. We need to remove the oov dimensions.
self._converter = converters.TrialToArrayConverter.from_study_config(
study_config, pad_oovs=False)
self._trials = tuple()
self._emukit_space = core.ParameterSpace(
[_to_emukit_parameter(spec) for spec in self._converter.output_specs])
self._metadata_ns = metadata_ns
self._num_random_samples = num_random_samples
def update(self, trials: vza.CompletedTrials) -> None:
self._trials += tuple(trials.completed)
def _suggest_random(self, count: int) -> Sequence[vz.TrialSuggestion]:
sampler = RandomDesign(self._emukit_space) # Collect random points
samples = sampler.get_samples(count)
return self._to_suggestions(samples, 'random')
def _to_suggestions(self, arr: np.ndarray,
source: str) -> Sequence[vz.TrialSuggestion]:
"""Convert arrays to suggestions and record the source."""
suggestions = []
for params in self._converter.to_parameters(arr):
suggestion = vz.TrialSuggestion(params)
suggestion.metadata.ns(self._metadata_ns)['source'] = source
suggestions.append(suggestion)
return suggestions
def _suggest_bayesopt(self,
count: Optional[int] = None
) -> Sequence[vz.TrialSuggestion]:
features, labels = self._converter.to_xy(self._trials)
# emukit minimizes. Flip the signs.
labels = -labels
if self._version == Version.DEFAULT_EI:
gpy_model = models.GPRegression(features, labels)
emukit_model = model_wrappers.GPyModelWrapper(gpy_model)
acquisition = acquisitions.ExpectedImprovement(model=emukit_model)
elif self._version == Version.MATERN52_UCB:
gpy_model = _create_constrained_gp(features, labels)
emukit_model = model_wrappers.GPyModelWrapper(gpy_model, n_restarts=20)
acquisition = acquisitions.NegativeLowerConfidenceBound(
model=emukit_model, beta=np.float64(1.8))
logging.info(
'Emukit model: model=%s',
# Values associated with length-1 keys are useless.
{k: v for k, v in emukit_model.model.to_dict().items() if len(k) > 1})
logging.info('Gpy model: model=%s', gpy_model)
bayesopt_loop = loops.BayesianOptimizationLoop(
model=emukit_model,
space=self._emukit_space,
acquisition=acquisition,
batch_size=count or 1)
x1 = bayesopt_loop.get_next_points([])
return self._to_suggestions(x1, 'bayesopt')
def suggest(self,
count: Optional[int] = None) -> Sequence[vz.TrialSuggestion]:
if len(self._trials) < self._num_random_samples:
return self._suggest_random(
count or (self._num_random_samples - len(self._trials)))
try:
return self._suggest_bayesopt(count)
except np.linalg.LinAlgError as e:
logging.exception('Training failed: %s', e)
return self._suggest_random(count or 1)
| [
"GPy.kern.Matern52",
"absl.logging.logging.getLogger",
"numpy.ones",
"absl.logging.info",
"emukit.core.ParameterSpace",
"numpy.float64",
"GPy.util.linalg.pdinv",
"absl.logging.exception",
"vizier.pyvizier.converters.TrialToArrayConverter.from_study_config",
"GPy.core.parameterization.priors.LogGau... | [((2027, 2084), 'GPy.kern.Matern52', 'kern.Matern52', (['features.shape[1]'], {'variance': '(0.04)', 'ARD': '(True)'}), '(features.shape[1], variance=0.04, ARD=True)\n', (2040, 2084), False, 'from GPy import kern\n'), ((2443, 2506), 'GPy.models.GPRegression', 'models.GPRegression', (['features', 'labels', 'kernel'], {'noise_var': '(0.0039)'}), '(features, labels, kernel, noise_var=0.0039)\n', (2462, 2506), False, 'from GPy import models\n'), ((2754, 2828), 'absl.logging.info', 'logging.info', (['"""After train: %s, %s"""', 'gpy_model', 'gpy_model.kern.lengthscale'], {}), "('After train: %s, %s', gpy_model, gpy_model.kern.lengthscale)\n", (2766, 2828), False, 'from absl import logging\n'), ((3511, 3542), 'emukit.core.ParameterSpace', 'core.ParameterSpace', (['parameters'], {}), '(parameters)\n', (3530, 3542), False, 'from emukit import core\n'), ((2142, 2170), 'numpy.zeros', 'np.zeros', (['features.shape[1:]'], {}), '(features.shape[1:])\n', (2150, 2170), True, 'import numpy as np\n'), ((2350, 2379), 'GPy.core.parameterization.priors.LogGaussian', 'priors.LogGaussian', (['(-3.2)', '(4.6)'], {}), '(-3.2, 4.6)\n', (2368, 2379), False, 'from GPy.core.parameterization import priors\n'), ((2586, 2621), 'GPy.core.parameterization.priors.LogGaussian', 'priors.LogGaussian', (['(-5.5)'], {'sigma': '(4.6)'}), '(-5.5, sigma=4.6)\n', (2604, 2621), False, 'from GPy.core.parameterization import priors\n'), ((4802, 4887), 'vizier.pyvizier.converters.TrialToArrayConverter.from_study_config', 'converters.TrialToArrayConverter.from_study_config', (['study_config'], {'pad_oovs': '(False)'}), '(study_config, pad_oovs=False\n )\n', (4852, 4887), False, 'from vizier.pyvizier import converters\n'), ((6892, 6938), 'absl.logging.info', 'logging.info', (['"""Gpy model: model=%s"""', 'gpy_model'], {}), "('Gpy model: model=%s', gpy_model)\n", (6904, 6938), False, 'from absl import logging\n'), ((6960, 7088), 'emukit.bayesian_optimization.loops.BayesianOptimizationLoop', 'loops.BayesianOptimizationLoop', ([], {'model': 'emukit_model', 'space': 'self._emukit_space', 'acquisition': 'acquisition', 'batch_size': '(count or 1)'}), '(model=emukit_model, space=self._emukit_space,\n acquisition=acquisition, batch_size=count or 1)\n', (6990, 7088), False, 'from emukit.bayesian_optimization import loops\n'), ((841, 892), 'absl.logging.logging.getLogger', 'logging.logging.getLogger', (['"""paramz.transformations"""'], {}), "('paramz.transformations')\n", (866, 892), False, 'from absl import logging\n'), ((1351, 1375), 'GPy.util.linalg.pdinv', 'linalg.pdinv', (['self.sigma'], {}), '(self.sigma)\n', (1363, 1375), False, 'from GPy.util import linalg\n'), ((1396, 1417), 'numpy.square', 'np.square', (['self.sigma'], {}), '(self.sigma)\n', (1405, 1417), True, 'import numpy as np\n'), ((3202, 3269), 'emukit.core.ContinuousParameter', 'core.ContinuousParameter', (['spec.name', 'spec.bounds[0]', 'spec.bounds[1]'], {}), '(spec.name, spec.bounds[0], spec.bounds[1])\n', (3226, 3269), False, 'from emukit import core\n'), ((5742, 5768), 'vizier.pyvizier.TrialSuggestion', 'vz.TrialSuggestion', (['params'], {}), '(params)\n', (5760, 5768), True, 'from vizier import pyvizier as vz\n'), ((6220, 6257), 'GPy.models.GPRegression', 'models.GPRegression', (['features', 'labels'], {}), '(features, labels)\n', (6239, 6257), False, 'from GPy import models\n'), ((6279, 6320), 'emukit.model_wrappers.GPyModelWrapper', 'model_wrappers.GPyModelWrapper', (['gpy_model'], {}), '(gpy_model)\n', (6309, 6320), False, 'from emukit import model_wrappers\n'), ((6341, 6393), 'emukit.bayesian_optimization.acquisitions.ExpectedImprovement', 'acquisitions.ExpectedImprovement', ([], {'model': 'emukit_model'}), '(model=emukit_model)\n', (6373, 6393), False, 'from emukit.bayesian_optimization import acquisitions\n'), ((1560, 1569), 'numpy.log', 'np.log', (['x'], {}), '(x)\n', (1566, 1569), True, 'import numpy as np\n'), ((1780, 1789), 'numpy.log', 'np.log', (['x'], {}), '(x)\n', (1786, 1789), True, 'import numpy as np\n'), ((1814, 1833), 'numpy.dot', 'np.dot', (['self.inv', 'd'], {}), '(self.inv, d)\n', (1820, 1833), True, 'import numpy as np\n'), ((6523, 6579), 'emukit.model_wrappers.GPyModelWrapper', 'model_wrappers.GPyModelWrapper', (['gpy_model'], {'n_restarts': '(20)'}), '(gpy_model, n_restarts=20)\n', (6553, 6579), False, 'from emukit import model_wrappers\n'), ((7560, 7603), 'absl.logging.exception', 'logging.exception', (['"""Training failed: %s"""', 'e'], {}), "('Training failed: %s', e)\n", (7577, 7603), False, 'from absl import logging\n'), ((1528, 1539), 'numpy.array', 'np.array', (['x'], {}), '(x)\n', (1536, 1539), True, 'import numpy as np\n'), ((1687, 1706), 'numpy.dot', 'np.dot', (['self.inv', 'd'], {}), '(self.inv, d)\n', (1693, 1706), True, 'import numpy as np\n'), ((1748, 1759), 'numpy.array', 'np.array', (['x'], {}), '(x)\n', (1756, 1759), True, 'import numpy as np\n'), ((2192, 2219), 'numpy.ones', 'np.ones', (['features.shape[1:]'], {}), '(features.shape[1:])\n', (2199, 2219), True, 'import numpy as np\n'), ((1463, 1480), 'numpy.log', 'np.log', (['(2 * np.pi)'], {}), '(2 * np.pi)\n', (1469, 1480), True, 'import numpy as np\n'), ((6678, 6693), 'numpy.float64', 'np.float64', (['(1.8)'], {}), '(1.8)\n', (6688, 6693), True, 'import numpy as np\n')] |
import os
from matplotlib import pyplot as plt
import numpy as np
import seaborn as sns
import torch
sns.set(style='white')
def stat_plot(x: np.array, y: np.array, mode: str=''):
y_mean, y_std = np.transpose(np.mean(y, axis=0)), np.transpose(np.std(y, axis=0))
palette = sns.color_palette('husl', y_mean.shape[0])
for i in range(y_mean.shape[0]):
ax = sns.lineplot(x=x, y=y_mean[i], color=palette[i])
ax.fill_between(x, y_mean[i] + y_std[i], y_mean[i] - y_std[i], color=palette[i], alpha=0.1)
if mode == 'offline':
ax = sns.lineplot(x=x, y=np.full_like(x, 162), color='gray', linestyle='--')
ax.fill_between(x, np.full_like(x, 162 + 195), np.full_like(x, 162 - 195), color='gray', alpha=0.1)
plt.locator_params(axis='x', nbins=5)
plt.locator_params(axis='y', nbins=6)
plt.xticks(fontsize=18)
plt.yticks(fontsize=18)
plt.xlabel('Step (x 1000)', fontsize=22)
if mode in ['imitation', 'offline']: # Make x-axis labels "invisible" for IL/offline RL (retains spacing, unlike removing the x ticks/label)
ax.tick_params(axis='x', colors='white')
ax.xaxis.label.set_color('white')
plt.ylabel('Return', fontsize=22)
plt.margins(x=0)
plt.ylim(0, 500)
plt.tight_layout()
plt.savefig(f'results/{mode}/{mode}.png')
plt.close()
train_start, step, test_interval = 10000, 200000, 10000
for mode in ['online', 'imitation', 'offline', 'goal', 'meta']:
test_returns = []
x = np.arange(100) if mode in ['imitation', 'offline'] else np.arange(train_start, step + 1, test_interval) / 1000
for filename in os.listdir(f'results/{mode}'):
if 'metrics.pth' in filename:
test_returns.append(torch.load(f'results/{mode}/{filename}')['test_returns'])
if mode in ['imitation', 'offline']: test_returns[-1] = 100 * test_returns[-1]
y = np.array(test_returns)
stat_plot(x, y, mode)
| [
"seaborn.lineplot",
"matplotlib.pyplot.margins",
"numpy.mean",
"numpy.arange",
"matplotlib.pyplot.tight_layout",
"numpy.full_like",
"matplotlib.pyplot.locator_params",
"numpy.std",
"matplotlib.pyplot.close",
"torch.load",
"matplotlib.pyplot.yticks",
"matplotlib.pyplot.xticks",
"seaborn.set",... | [((104, 126), 'seaborn.set', 'sns.set', ([], {'style': '"""white"""'}), "(style='white')\n", (111, 126), True, 'import seaborn as sns\n'), ((280, 322), 'seaborn.color_palette', 'sns.color_palette', (['"""husl"""', 'y_mean.shape[0]'], {}), "('husl', y_mean.shape[0])\n", (297, 322), True, 'import seaborn as sns\n'), ((724, 761), 'matplotlib.pyplot.locator_params', 'plt.locator_params', ([], {'axis': '"""x"""', 'nbins': '(5)'}), "(axis='x', nbins=5)\n", (742, 761), True, 'from matplotlib import pyplot as plt\n'), ((764, 801), 'matplotlib.pyplot.locator_params', 'plt.locator_params', ([], {'axis': '"""y"""', 'nbins': '(6)'}), "(axis='y', nbins=6)\n", (782, 801), True, 'from matplotlib import pyplot as plt\n'), ((804, 827), 'matplotlib.pyplot.xticks', 'plt.xticks', ([], {'fontsize': '(18)'}), '(fontsize=18)\n', (814, 827), True, 'from matplotlib import pyplot as plt\n'), ((830, 853), 'matplotlib.pyplot.yticks', 'plt.yticks', ([], {'fontsize': '(18)'}), '(fontsize=18)\n', (840, 853), True, 'from matplotlib import pyplot as plt\n'), ((856, 896), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Step (x 1000)"""'], {'fontsize': '(22)'}), "('Step (x 1000)', fontsize=22)\n", (866, 896), True, 'from matplotlib import pyplot as plt\n'), ((1126, 1159), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Return"""'], {'fontsize': '(22)'}), "('Return', fontsize=22)\n", (1136, 1159), True, 'from matplotlib import pyplot as plt\n'), ((1162, 1178), 'matplotlib.pyplot.margins', 'plt.margins', ([], {'x': '(0)'}), '(x=0)\n', (1173, 1178), True, 'from matplotlib import pyplot as plt\n'), ((1181, 1197), 'matplotlib.pyplot.ylim', 'plt.ylim', (['(0)', '(500)'], {}), '(0, 500)\n', (1189, 1197), True, 'from matplotlib import pyplot as plt\n'), ((1200, 1218), 'matplotlib.pyplot.tight_layout', 'plt.tight_layout', ([], {}), '()\n', (1216, 1218), True, 'from matplotlib import pyplot as plt\n'), ((1221, 1262), 'matplotlib.pyplot.savefig', 'plt.savefig', (['f"""results/{mode}/{mode}.png"""'], {}), "(f'results/{mode}/{mode}.png')\n", (1232, 1262), True, 'from matplotlib import pyplot as plt\n'), ((1265, 1276), 'matplotlib.pyplot.close', 'plt.close', ([], {}), '()\n', (1274, 1276), True, 'from matplotlib import pyplot as plt\n'), ((1555, 1584), 'os.listdir', 'os.listdir', (['f"""results/{mode}"""'], {}), "(f'results/{mode}')\n", (1565, 1584), False, 'import os\n'), ((1795, 1817), 'numpy.array', 'np.array', (['test_returns'], {}), '(test_returns)\n', (1803, 1817), True, 'import numpy as np\n'), ((367, 415), 'seaborn.lineplot', 'sns.lineplot', ([], {'x': 'x', 'y': 'y_mean[i]', 'color': 'palette[i]'}), '(x=x, y=y_mean[i], color=palette[i])\n', (379, 415), True, 'import seaborn as sns\n'), ((1426, 1440), 'numpy.arange', 'np.arange', (['(100)'], {}), '(100)\n', (1435, 1440), True, 'import numpy as np\n'), ((215, 233), 'numpy.mean', 'np.mean', (['y'], {'axis': '(0)'}), '(y, axis=0)\n', (222, 233), True, 'import numpy as np\n'), ((249, 266), 'numpy.std', 'np.std', (['y'], {'axis': '(0)'}), '(y, axis=0)\n', (255, 266), True, 'import numpy as np\n'), ((640, 666), 'numpy.full_like', 'np.full_like', (['x', '(162 + 195)'], {}), '(x, 162 + 195)\n', (652, 666), True, 'import numpy as np\n'), ((668, 694), 'numpy.full_like', 'np.full_like', (['x', '(162 - 195)'], {}), '(x, 162 - 195)\n', (680, 694), True, 'import numpy as np\n'), ((1482, 1529), 'numpy.arange', 'np.arange', (['train_start', '(step + 1)', 'test_interval'], {}), '(train_start, step + 1, test_interval)\n', (1491, 1529), True, 'import numpy as np\n'), ((565, 585), 'numpy.full_like', 'np.full_like', (['x', '(162)'], {}), '(x, 162)\n', (577, 585), True, 'import numpy as np\n'), ((1646, 1686), 'torch.load', 'torch.load', (['f"""results/{mode}/{filename}"""'], {}), "(f'results/{mode}/{filename}')\n", (1656, 1686), False, 'import torch\n')] |
"""
File: examples/model/multi_conditional_fit_model.py
Author: <NAME>
Date: 5 Oct 2020
Description: Example script showing a use of the MultiConditionalFitModel
class.
"""
from __future__ import division
import numpy as np
import matplotlib.pyplot as pl
from matplotlib.ticker import MultipleLocator
from distpy import GaussianDistribution, DistributionSet
from pylinex import Basis, LegendreBasis, FourierBasis, BasisModel,\
GaussianModel, LorentzianModel, SumModel, ProductModel,\
MultiConditionalFitModel
fontsize = 24
triangle_plot_fontsize = 8
seed = 0
np.random.seed(seed)
include_noise = True
include_nuisance_prior = False
include_offset_prior = False
num_channels = 1001
xs = np.linspace(-1, 1, num_channels)
num_nuisance_terms = 5
num_offset_terms = 5
gain_model = LorentzianModel(xs)
nuisance_model =\
BasisModel(LegendreBasis(num_channels, num_nuisance_terms - 1))
signal_model = GaussianModel(xs)
ideal_model = SumModel(['signal', 'nuisance'], [signal_model, nuisance_model])
multiplicative_model =\
ProductModel(['gain', 'ideal'], [gain_model, ideal_model])
#offset_model = BasisModel(FourierBasis(num_channels, 30)[1+num_nuisance_terms:1+num_nuisance_terms+num_offset_terms])
offset_model = BasisModel(FourierBasis(num_channels, 30)[1:1+num_offset_terms])
full_model = SumModel(['multiplicative', 'offset'],\
[multiplicative_model, offset_model])
true_gain_parameters = np.array([1, 0.2, 2])
true_signal_parameters = np.array([-1, 0, 0.3])
true_nuisance_parameters = np.random.normal(0, 10, size=num_nuisance_terms)
true_offset_parameters = np.random.normal(0, 10, size=num_offset_terms)
true_gain = gain_model(true_gain_parameters)
true_signal = signal_model(true_signal_parameters)
true_nuisance = nuisance_model(true_nuisance_parameters)
true_offset = offset_model(true_offset_parameters)
noiseless_data = (true_gain * (true_signal + true_nuisance)) + true_offset
error = np.ones_like(xs)
if include_noise:
true_noise = np.random.normal(0, 1, size=num_channels) * error
else:
true_noise = np.zeros(num_channels)
data = noiseless_data + true_noise
unknown_name_chains = [['multiplicative', 'ideal', 'nuisance'], ['offset']]
if include_nuisance_prior:
nuisance_prior_covariance =\
0.9 * np.ones((num_nuisance_terms, num_nuisance_terms))
for index in range(num_nuisance_terms):
nuisance_prior_covariance[index,index] = 1
nuisance_prior = GaussianDistribution(true_nuisance_parameters,\
nuisance_prior_covariance)
else:
nuisance_prior = None
if include_offset_prior:
offset_prior_covariance =\
0.9 * np.ones((num_offset_terms, num_offset_terms))
for index in range(num_offset_terms):
offset_prior_covariance[index,index] = 1
offset_prior = GaussianDistribution(true_offset_parameters,\
offset_prior_covariance)
else:
offset_prior = None
priors = [nuisance_prior, offset_prior]
model = MultiConditionalFitModel(full_model, data, error, unknown_name_chains,\
priors=priors)
(recreation, conditional_mean, conditional_covariance,\
log_prior_at_conditional_mean) = model(np.concatenate(\
[true_gain_parameters, true_signal_parameters]),\
return_conditional_mean=True, return_conditional_covariance=True,\
return_log_prior_at_conditional_mean=True)
input_unknown_parameters =\
np.concatenate([true_nuisance_parameters, true_offset_parameters])
conditional_distribution =\
GaussianDistribution(conditional_mean, conditional_covariance)
unknown_parameters = sum([[parameter for parameter in full_model.parameters\
if '_'.join(name_chain) in parameter]\
for name_chain in unknown_name_chains], [])
conditional_distribution_set =\
DistributionSet([(conditional_distribution, unknown_parameters)])
num_samples = int(1e6)
fig = conditional_distribution_set.triangle_plot(num_samples,\
reference_value_mean=input_unknown_parameters, nbins=200,\
fontsize=triangle_plot_fontsize, contour_confidence_levels=[0.68, 0.95],\
parameter_renamer=(lambda parameter: '_'.join(parameter.split('_')[-2:])))
conditional_distribution_set.triangle_plot(num_samples, fig=fig,\
reference_value_mean=input_unknown_parameters, nbins=200,\
fontsize=triangle_plot_fontsize, plot_type='histogram',\
parameter_renamer=(lambda parameter: '_'.join(parameter.split('_')[-2:])))
if not (include_nuisance_prior or include_offset_prior):
assert(np.isclose(log_prior_at_conditional_mean, 0))
fig = pl.figure(figsize=(12,9))
ax = fig.add_subplot(211)
ax.scatter(xs, data, color='k', label='with noise')
ax.scatter(xs, noiseless_data, color='C0', label='without noise')
ax.plot(xs, recreation, color='C2', label='recreation')
ax.set_xlim((xs[0], xs[-1]))
ax.set_xlabel('$x$', size=fontsize)
ax.set_ylabel('$y$', size=fontsize)
ax.tick_params(labelsize=fontsize, width=2.5, length=7.5, which='major')
ax.tick_params(labelsize=fontsize, width=1.5, length=4.5, which='minor')
ax.xaxis.set_major_locator(MultipleLocator(0.5))
ax.xaxis.set_minor_locator(MultipleLocator(0.1))
ax.legend(fontsize=fontsize)
ax = fig.add_subplot(212)
ax.scatter(xs, data - recreation, color='k', label='with noise')
ax.scatter(xs, noiseless_data - recreation, color='C0', label='without noise')
ax.set_xlim((xs[0], xs[-1]))
ax.set_xlabel('$x$', size=fontsize)
ax.set_ylabel('$\delta y$', size=fontsize)
ax.tick_params(labelsize=fontsize, width=2.5, length=7.5, which='major')
ax.tick_params(labelsize=fontsize, width=1.5, length=4.5, which='minor')
ax.xaxis.set_major_locator(MultipleLocator(0.5))
ax.xaxis.set_minor_locator(MultipleLocator(0.1))
ax.legend(fontsize=fontsize)
fig.subplots_adjust(left=0.11, right=0.95, bottom=0.10, top=0.97, hspace=0.53)
pl.show()
| [
"numpy.random.seed",
"numpy.ones",
"matplotlib.pyplot.figure",
"pylinex.MultiConditionalFitModel",
"numpy.isclose",
"numpy.random.normal",
"pylinex.LegendreBasis",
"pylinex.SumModel",
"distpy.DistributionSet",
"numpy.linspace",
"pylinex.FourierBasis",
"matplotlib.ticker.MultipleLocator",
"py... | [((583, 603), 'numpy.random.seed', 'np.random.seed', (['seed'], {}), '(seed)\n', (597, 603), True, 'import numpy as np\n'), ((712, 744), 'numpy.linspace', 'np.linspace', (['(-1)', '(1)', 'num_channels'], {}), '(-1, 1, num_channels)\n', (723, 744), True, 'import numpy as np\n'), ((804, 823), 'pylinex.LorentzianModel', 'LorentzianModel', (['xs'], {}), '(xs)\n', (819, 823), False, 'from pylinex import Basis, LegendreBasis, FourierBasis, BasisModel, GaussianModel, LorentzianModel, SumModel, ProductModel, MultiConditionalFitModel\n'), ((925, 942), 'pylinex.GaussianModel', 'GaussianModel', (['xs'], {}), '(xs)\n', (938, 942), False, 'from pylinex import Basis, LegendreBasis, FourierBasis, BasisModel, GaussianModel, LorentzianModel, SumModel, ProductModel, MultiConditionalFitModel\n'), ((957, 1021), 'pylinex.SumModel', 'SumModel', (["['signal', 'nuisance']", '[signal_model, nuisance_model]'], {}), "(['signal', 'nuisance'], [signal_model, nuisance_model])\n", (965, 1021), False, 'from pylinex import Basis, LegendreBasis, FourierBasis, BasisModel, GaussianModel, LorentzianModel, SumModel, ProductModel, MultiConditionalFitModel\n'), ((1050, 1108), 'pylinex.ProductModel', 'ProductModel', (["['gain', 'ideal']", '[gain_model, ideal_model]'], {}), "(['gain', 'ideal'], [gain_model, ideal_model])\n", (1062, 1108), False, 'from pylinex import Basis, LegendreBasis, FourierBasis, BasisModel, GaussianModel, LorentzianModel, SumModel, ProductModel, MultiConditionalFitModel\n'), ((1321, 1397), 'pylinex.SumModel', 'SumModel', (["['multiplicative', 'offset']", '[multiplicative_model, offset_model]'], {}), "(['multiplicative', 'offset'], [multiplicative_model, offset_model])\n", (1329, 1397), False, 'from pylinex import Basis, LegendreBasis, FourierBasis, BasisModel, GaussianModel, LorentzianModel, SumModel, ProductModel, MultiConditionalFitModel\n'), ((1427, 1448), 'numpy.array', 'np.array', (['[1, 0.2, 2]'], {}), '([1, 0.2, 2])\n', (1435, 1448), True, 'import numpy as np\n'), ((1474, 1496), 'numpy.array', 'np.array', (['[-1, 0, 0.3]'], {}), '([-1, 0, 0.3])\n', (1482, 1496), True, 'import numpy as np\n'), ((1524, 1572), 'numpy.random.normal', 'np.random.normal', (['(0)', '(10)'], {'size': 'num_nuisance_terms'}), '(0, 10, size=num_nuisance_terms)\n', (1540, 1572), True, 'import numpy as np\n'), ((1598, 1644), 'numpy.random.normal', 'np.random.normal', (['(0)', '(10)'], {'size': 'num_offset_terms'}), '(0, 10, size=num_offset_terms)\n', (1614, 1644), True, 'import numpy as np\n'), ((1935, 1951), 'numpy.ones_like', 'np.ones_like', (['xs'], {}), '(xs)\n', (1947, 1951), True, 'import numpy as np\n'), ((2937, 3026), 'pylinex.MultiConditionalFitModel', 'MultiConditionalFitModel', (['full_model', 'data', 'error', 'unknown_name_chains'], {'priors': 'priors'}), '(full_model, data, error, unknown_name_chains,\n priors=priors)\n', (2961, 3026), False, 'from pylinex import Basis, LegendreBasis, FourierBasis, BasisModel, GaussianModel, LorentzianModel, SumModel, ProductModel, MultiConditionalFitModel\n'), ((3350, 3416), 'numpy.concatenate', 'np.concatenate', (['[true_nuisance_parameters, true_offset_parameters]'], {}), '([true_nuisance_parameters, true_offset_parameters])\n', (3364, 3416), True, 'import numpy as np\n'), ((3450, 3512), 'distpy.GaussianDistribution', 'GaussianDistribution', (['conditional_mean', 'conditional_covariance'], {}), '(conditional_mean, conditional_covariance)\n', (3470, 3512), False, 'from distpy import GaussianDistribution, DistributionSet\n'), ((3717, 3782), 'distpy.DistributionSet', 'DistributionSet', (['[(conditional_distribution, unknown_parameters)]'], {}), '([(conditional_distribution, unknown_parameters)])\n', (3732, 3782), False, 'from distpy import GaussianDistribution, DistributionSet\n'), ((4480, 4506), 'matplotlib.pyplot.figure', 'pl.figure', ([], {'figsize': '(12, 9)'}), '(figsize=(12, 9))\n', (4489, 4506), True, 'import matplotlib.pyplot as pl\n'), ((5714, 5723), 'matplotlib.pyplot.show', 'pl.show', ([], {}), '()\n', (5721, 5723), True, 'import matplotlib.pyplot as pl\n'), ((857, 908), 'pylinex.LegendreBasis', 'LegendreBasis', (['num_channels', '(num_nuisance_terms - 1)'], {}), '(num_channels, num_nuisance_terms - 1)\n', (870, 908), False, 'from pylinex import Basis, LegendreBasis, FourierBasis, BasisModel, GaussianModel, LorentzianModel, SumModel, ProductModel, MultiConditionalFitModel\n'), ((2060, 2082), 'numpy.zeros', 'np.zeros', (['num_channels'], {}), '(num_channels)\n', (2068, 2082), True, 'import numpy as np\n'), ((2436, 2509), 'distpy.GaussianDistribution', 'GaussianDistribution', (['true_nuisance_parameters', 'nuisance_prior_covariance'], {}), '(true_nuisance_parameters, nuisance_prior_covariance)\n', (2456, 2509), False, 'from distpy import GaussianDistribution, DistributionSet\n'), ((2778, 2847), 'distpy.GaussianDistribution', 'GaussianDistribution', (['true_offset_parameters', 'offset_prior_covariance'], {}), '(true_offset_parameters, offset_prior_covariance)\n', (2798, 2847), False, 'from distpy import GaussianDistribution, DistributionSet\n'), ((3128, 3190), 'numpy.concatenate', 'np.concatenate', (['[true_gain_parameters, true_signal_parameters]'], {}), '([true_gain_parameters, true_signal_parameters])\n', (3142, 3190), True, 'import numpy as np\n'), ((4427, 4471), 'numpy.isclose', 'np.isclose', (['log_prior_at_conditional_mean', '(0)'], {}), '(log_prior_at_conditional_mean, 0)\n', (4437, 4471), True, 'import numpy as np\n'), ((4981, 5001), 'matplotlib.ticker.MultipleLocator', 'MultipleLocator', (['(0.5)'], {}), '(0.5)\n', (4996, 5001), False, 'from matplotlib.ticker import MultipleLocator\n'), ((5030, 5050), 'matplotlib.ticker.MultipleLocator', 'MultipleLocator', (['(0.1)'], {}), '(0.1)\n', (5045, 5050), False, 'from matplotlib.ticker import MultipleLocator\n'), ((5533, 5553), 'matplotlib.ticker.MultipleLocator', 'MultipleLocator', (['(0.5)'], {}), '(0.5)\n', (5548, 5553), False, 'from matplotlib.ticker import MultipleLocator\n'), ((5582, 5602), 'matplotlib.ticker.MultipleLocator', 'MultipleLocator', (['(0.1)'], {}), '(0.1)\n', (5597, 5602), False, 'from matplotlib.ticker import MultipleLocator\n'), ((1254, 1284), 'pylinex.FourierBasis', 'FourierBasis', (['num_channels', '(30)'], {}), '(num_channels, 30)\n', (1266, 1284), False, 'from pylinex import Basis, LegendreBasis, FourierBasis, BasisModel, GaussianModel, LorentzianModel, SumModel, ProductModel, MultiConditionalFitModel\n'), ((1987, 2028), 'numpy.random.normal', 'np.random.normal', (['(0)', '(1)'], {'size': 'num_channels'}), '(0, 1, size=num_channels)\n', (2003, 2028), True, 'import numpy as np\n'), ((2270, 2319), 'numpy.ones', 'np.ones', (['(num_nuisance_terms, num_nuisance_terms)'], {}), '((num_nuisance_terms, num_nuisance_terms))\n', (2277, 2319), True, 'import numpy as np\n'), ((2622, 2667), 'numpy.ones', 'np.ones', (['(num_offset_terms, num_offset_terms)'], {}), '((num_offset_terms, num_offset_terms))\n', (2629, 2667), True, 'import numpy as np\n')] |
import numpy as np
import sklearn
sign_defaults = {
"keep positive": 1,
"keep negative": -1,
"remove positive": -1,
"remove negative": 1,
"compute time": -1,
"keep absolute": -1, # the absolute signs are defaults that make sense when scoring losses
"remove absolute": 1,
"explanation error": -1
}
class BenchmarkResult():
""" The result of a benchmark run.
"""
def __init__(self, metric, method, value=None, curve_x=None, curve_y=None, curve_y_std=None, value_sign=None):
self.metric = metric
self.method = method
self.value = value
self.curve_x = curve_x
self.curve_y = curve_y
self.curve_y_std = curve_y_std
self.value_sign = value_sign
if self.value_sign is None and self.metric in sign_defaults:
self.value_sign = sign_defaults[self.metric]
if self.value is None:
self.value = sklearn.metrics.auc(curve_x, (np.array(curve_y) - curve_y[0]))
@property
def full_name(self):
return self.method + " " + self.metric
| [
"numpy.array"
] | [((954, 971), 'numpy.array', 'np.array', (['curve_y'], {}), '(curve_y)\n', (962, 971), True, 'import numpy as np\n')] |
#!/usr/bin/env python
"""
tokio.timeseries.TimeSeries methods
"""
import datetime
import random
import pandas
import nose
import numpy
import tokio
from tokiotest import generate_timeseries, compare_timeseries
START = datetime.datetime(2019, 5, 28, 1, 0, 0)
END = datetime.datetime(2019, 5, 28, 2, 0, 0)
DELTIM = datetime.timedelta(seconds=10)
def to_dataframe(timeseries):
return pandas.DataFrame(
timeseries.dataset,
index=[datetime.datetime.fromtimestamp(x) for x in timeseries.timestamps],
columns=timeseries.columns)
def test_rearrange():
"""
TimeSeries.rearrange_columns()
"""
timeseries1 = generate_timeseries()
timeseries2 = generate_timeseries()
# test random reordering
new_col_order = list(timeseries2.columns[:])
print(new_col_order)
random.shuffle(new_col_order)
print(new_col_order)
timeseries2.rearrange_columns(new_col_order)
print("Comparing before/after rearrange_columns()")
compare_timeseries(timeseries2, timeseries1, verbose=True)
def test_sort():
"""
TimeSeries.sort_columns()
"""
timeseries1 = generate_timeseries()
timeseries2 = generate_timeseries()
timeseries2.sort_columns()
print("Comparing before/after sort_columns()")
compare_timeseries(timeseries2, timeseries1, verbose=True)
def test_timeseries_deltas():
"""
TimeSeries.timeseries_deltas()
"""
max_delta = 9
num_cols = 16
num_rows = 20
numpy.set_printoptions(formatter={'float': '{: 0.1f}'.format})
random.seed(0)
# Create an array of random deltas as our ground truth
actual_deltas = numpy.random.random(size=(num_rows, num_cols)) * max_delta
first_row = numpy.random.random(size=(1, num_cols)) * max_delta
# actual_deltas = numpy.full((num_rows, num_cols), 2.0)
# first_row = numpy.full((1, num_cols), 2.0)
# Calculate the monotonically increasing dataset that would result in these deltas
monotonic_values = actual_deltas.copy()
monotonic_values = numpy.vstack((first_row, actual_deltas)).copy()
for irow in range(1, monotonic_values.shape[0]):
monotonic_values[irow, :] += monotonic_values[irow - 1, :]
print("Actual monotonic values:")
print(monotonic_values)
print()
print("Actual deltas:")
print(actual_deltas)
print()
# Delete some data from our sample monotonically increasing dataset
# Columns 0-3 are hand-picked to exercise all edge cases
delete_data = [
(1, 0),
(2, 0),
(5, 0),
(0, 1),
(1, 1),
(1, 2),
(3, 2),
(-1, 2),
(-2, 2),
(0, 3),
(-1, 3),
]
# Columns 4-7 are low density errors
for _ in range(int(num_cols * num_rows / 4)):
delete_data.append((numpy.random.randint(0, num_rows), numpy.random.randint(4, 8)))
# Columns 8-11 are high density errors
for _ in range(int(3 * num_cols * num_rows / 4)):
delete_data.append((numpy.random.randint(0, num_rows), numpy.random.randint(8, 12)))
### Note that this method produces bad data if the input data is non-monotonic
### in time. It would need some small tweaks to deal with that, so in the meantime,
### just don't do it.
# Columns 12-15 are nonzero but non-monotonic flips
start_flip = 12
# flip_data = []
# for _ in range(int(3 * num_cols * num_rows / 4)):
# flip_data.append((numpy.random.randint(0, num_rows), numpy.random.randint(12, 16)))
for coordinates in delete_data:
monotonic_values[coordinates] = 0.0
print("Matrix after introducing data loss:")
print(monotonic_values)
print()
# for irow, icol in flip_data:
# if irow == 0:
# irow_complement = irow + 1
# else:
# irow_complement = irow - 1
# temp = monotonic_values[irow, icol]
# monotonic_values[irow, icol] = monotonic_values[irow_complement, icol]
# monotonic_values[irow_complement, icol] = temp
# print "Flipping the following:"
# print flip_data
# print
# print "Matrix after flipping data order:"
# print monotonic_values
# print
# Call the routine being tested to regenerate the deltas matrix
calculated_deltas = tokio.timeseries.timeseries_deltas(monotonic_values)
# Check to make sure that the total data moved according to our function
# matches the logical total obtained by subtracting the largest absolute
# measurement from the smallest
print("Checking each column's sum (missing data)")
for icol in range(start_flip):
truth = actual_deltas[:, icol].sum()
calculated = calculated_deltas[:, icol].sum()
total_delta = monotonic_values[:, icol].max() \
- numpy.matrix([x for x in monotonic_values[:, icol] if x > 0.0]).min()
print('truth=%s from piecewise deltas=%s from total delta=%s' % (
truth,
calculated,
total_delta))
assert numpy.isclose(calculated, total_delta)
# Calculated delta should either be equal to (no data loss) or less than
# (data lost) than ground truth. It should never reflect MORE total
# than the ground truth.
assert numpy.isclose(truth - calculated, 0.0) or ((truth - calculated) > 0)
print("Checking each column's sum (flipped data)")
for icol in range(start_flip, actual_deltas.shape[1]):
truth = actual_deltas[:, icol].sum()
calculated = calculated_deltas[:, icol].sum()
total_delta = monotonic_values[:, icol].max() \
- numpy.matrix([x for x in monotonic_values[:, icol] if x > 0.0]).min()
print('truth=%s from piecewise deltas=%s from total delta=%s' % (
truth,
calculated,
total_delta))
assert numpy.isclose(calculated, total_delta) or ((total_delta - calculated) > 0)
assert numpy.isclose(truth, calculated) or ((truth - calculated) > 0)
# Now do an element-by-element comparison
close_matrix = numpy.isclose(calculated_deltas, actual_deltas)
print("Is each calculated delta close to the ground-truth deltas?")
print(close_matrix)
print()
# Some calculated values will _not_ be the same because the data loss we
# induced, well, loses data. However we can account for known differences
# and ensure that nothing unexpected is different.
fix_matrix = numpy.full(close_matrix.shape, False)
for irow, icol in delete_data: #+ flip_data:
fix_matrix[irow, icol] = True
if irow - 1 >= 0:
fix_matrix[irow - 1, icol] = True
# for irow, icol in flip_data:
# if irow == 0:
# fix_matrix[irow + 1, icol] = True
print("Matrix of known deviations from the ground truth:")
print(fix_matrix)
print()
print("Non-missing and known-missing data (everything should be True):")
print(close_matrix | fix_matrix)
print()
assert (close_matrix | fix_matrix).all()
def test_add_rows():
"""
TimeSeries.add_rows()
"""
add_rows = 5
timeseries = generate_timeseries()
orig_row = timeseries.timestamps.copy()
orig_row_count = timeseries.timestamps.shape[0]
timeseries.add_rows(add_rows)
prev_deltim = None
for index in range(1, timeseries.dataset.shape[0]):
new_deltim = timeseries.timestamps[index] - timeseries.timestamps[index - 1]
if prev_deltim is not None:
assert new_deltim == prev_deltim
prev_deltim = new_deltim
print("Orig timestamps: %s" % orig_row[-5: -1])
print("Now timestamps: %s" % timeseries.timestamps[-5 - add_rows: -1])
assert prev_deltim > 0
assert timeseries.timestamps.shape[0] == timeseries.dataset.shape[0]
assert (timeseries.timestamps.shape[0] - add_rows) == orig_row_count
def _test_insert_element(timeseries, timestamp, column_name, value, reducer, expect_failure):
worked = timeseries.insert_element(
timestamp=timestamp,
column_name=column_name,
value=value,
reducer=reducer)
print("worked? ", worked)
if expect_failure:
assert not worked
else:
assert worked
def test_insert_element():
"""TimeSeries.insert_element()
"""
timeseries = tokio.timeseries.TimeSeries(
dataset_name='test_dataset',
start=START,
end=END,
timestep=DELTIM.total_seconds(),
num_columns=5,
column_names=['a', 'b', 'c', 'd', 'e'])
func = _test_insert_element
func.description = "TimeSeries.insert_element(): insert element at first position"
yield func, timeseries, START, 'a', 1.0, None, False
func.description = "TimeSeries.insert_element(): insert element at last position"
yield func, timeseries, END - DELTIM, 'a', 1.0, None, False
func.description = "TimeSeries.insert_element(): insert element at negative position"
yield func, timeseries, START - DELTIM, 'a', 1.0, None, True
func.description = "TimeSeries.insert_element(): insert element beyond end position"
yield func, timeseries, END, 'a', 1.0, None, True
def test_insert_element_columns():
"""TimeSeries.insert_element(): insert element in column that does fit"""
timeseries = tokio.timeseries.TimeSeries(
dataset_name='test_dataset',
start=START,
end=END,
timestep=DELTIM.total_seconds(),
num_columns=6,
column_names=['a', 'b', 'c', 'd', 'e'])
_test_insert_element(timeseries, START + DELTIM, 'f', 1.0, None, False)
assert 'f' in timeseries.columns
@nose.tools.raises(IndexError)
def test_insert_element_column_overflow():
"""TimeSeries.insert_element(): insert element in column that doesn't fit"""
timeseries = tokio.timeseries.TimeSeries(
dataset_name='test_dataset',
start=START,
end=END,
timestep=DELTIM.total_seconds(),
num_columns=5,
column_names=['a', 'b', 'c', 'd', 'e'])
_test_insert_element(timeseries, START + DELTIM, 'f', 1.0, None, True)
def test_align():
"""TimeSeries.insert_element() and TimeSeries.convert_deltas()
"""
# Test the case:
#
# +-----+-----+---
# | x | y |
# +-----+-----+---
# ^-t0 ^-t1
#
# yields
#
# +-----+-----+---
# | y-x | 0 |
# +-----+-----+---
# ^-t0 ^-t1
#
timeseries0 = tokio.timeseries.TimeSeries(
dataset_name='test_dataset',
start=START,
end=START + DELTIM * 3,
timestep=DELTIM.total_seconds(),
num_columns=5,
column_names=['a', 'b', 'c', 'd', 'e'])
assert timeseries0.insert_element(
timestamp=START,
column_name='a',
value=1.0,
reducer=None,
align='l')
assert timeseries0.insert_element(
timestamp=START + DELTIM,
column_name='a',
value=2.0,
reducer=None,
align='l')
print("\nDataset before delta conversion:")
print(to_dataframe(timeseries0))
timeseries0.convert_to_deltas(align='l')
print("\nDataset after delta conversion:")
print(to_dataframe(timeseries0))
assert timeseries0.dataset[0, 0]
assert not timeseries0.dataset[1, 0]
df0 = to_dataframe(timeseries0)
# Test the case:
#
# +-----+-----+---
# | x | y |
# +-----+-----+---
# ^-t0 ^-t1
#
# yields
#
# +-----+-----+---
# | y-x | 0 |
# +-----+-----+---
# ^-t0 ^-t1
#
timeseries1 = tokio.timeseries.TimeSeries(
dataset_name='test_dataset',
start=START,
end=START + DELTIM * 3,
timestep=DELTIM.total_seconds(),
num_columns=5,
column_names=['a', 'b', 'c', 'd', 'e'])
assert timeseries1.insert_element(
timestamp=START + DELTIM,
column_name='a',
value=1.0,
reducer=None,
align='r')
assert timeseries1.insert_element(
timestamp=START + 2 * DELTIM,
column_name='a',
value=2.0,
reducer=None,
align='r')
print("\nDataset before delta conversion:")
print(to_dataframe(timeseries1))
timeseries1.convert_to_deltas(align='l')
print("\nDataset after delta conversion:")
print(to_dataframe(timeseries1))
assert timeseries1.dataset[0, 0]
assert not timeseries1.dataset[1, 0]
df1 = to_dataframe(timeseries1)
assert (df0.index == df1.index).all()
assert (df0.all() == df1.all()).all()
| [
"numpy.full",
"numpy.matrix",
"numpy.set_printoptions",
"random.shuffle",
"tokiotest.compare_timeseries",
"datetime.datetime",
"numpy.isclose",
"numpy.random.random",
"datetime.timedelta",
"random.seed",
"numpy.random.randint",
"datetime.datetime.fromtimestamp",
"tokio.timeseries.timeseries_... | [((221, 260), 'datetime.datetime', 'datetime.datetime', (['(2019)', '(5)', '(28)', '(1)', '(0)', '(0)'], {}), '(2019, 5, 28, 1, 0, 0)\n', (238, 260), False, 'import datetime\n'), ((267, 306), 'datetime.datetime', 'datetime.datetime', (['(2019)', '(5)', '(28)', '(2)', '(0)', '(0)'], {}), '(2019, 5, 28, 2, 0, 0)\n', (284, 306), False, 'import datetime\n'), ((316, 346), 'datetime.timedelta', 'datetime.timedelta', ([], {'seconds': '(10)'}), '(seconds=10)\n', (334, 346), False, 'import datetime\n'), ((9549, 9578), 'nose.tools.raises', 'nose.tools.raises', (['IndexError'], {}), '(IndexError)\n', (9566, 9578), False, 'import nose\n'), ((646, 667), 'tokiotest.generate_timeseries', 'generate_timeseries', ([], {}), '()\n', (665, 667), False, 'from tokiotest import generate_timeseries, compare_timeseries\n'), ((686, 707), 'tokiotest.generate_timeseries', 'generate_timeseries', ([], {}), '()\n', (705, 707), False, 'from tokiotest import generate_timeseries, compare_timeseries\n'), ((816, 845), 'random.shuffle', 'random.shuffle', (['new_col_order'], {}), '(new_col_order)\n', (830, 845), False, 'import random\n'), ((981, 1039), 'tokiotest.compare_timeseries', 'compare_timeseries', (['timeseries2', 'timeseries1'], {'verbose': '(True)'}), '(timeseries2, timeseries1, verbose=True)\n', (999, 1039), False, 'from tokiotest import generate_timeseries, compare_timeseries\n'), ((1122, 1143), 'tokiotest.generate_timeseries', 'generate_timeseries', ([], {}), '()\n', (1141, 1143), False, 'from tokiotest import generate_timeseries, compare_timeseries\n'), ((1162, 1183), 'tokiotest.generate_timeseries', 'generate_timeseries', ([], {}), '()\n', (1181, 1183), False, 'from tokiotest import generate_timeseries, compare_timeseries\n'), ((1271, 1329), 'tokiotest.compare_timeseries', 'compare_timeseries', (['timeseries2', 'timeseries1'], {'verbose': '(True)'}), '(timeseries2, timeseries1, verbose=True)\n', (1289, 1329), False, 'from tokiotest import generate_timeseries, compare_timeseries\n'), ((1472, 1534), 'numpy.set_printoptions', 'numpy.set_printoptions', ([], {'formatter': "{'float': '{: 0.1f}'.format}"}), "(formatter={'float': '{: 0.1f}'.format})\n", (1494, 1534), False, 'import numpy\n'), ((1539, 1553), 'random.seed', 'random.seed', (['(0)'], {}), '(0)\n', (1550, 1553), False, 'import random\n'), ((4215, 4267), 'tokio.timeseries.timeseries_deltas', 'tokio.timeseries.timeseries_deltas', (['monotonic_values'], {}), '(monotonic_values)\n', (4249, 4267), False, 'import tokio\n'), ((6013, 6060), 'numpy.isclose', 'numpy.isclose', (['calculated_deltas', 'actual_deltas'], {}), '(calculated_deltas, actual_deltas)\n', (6026, 6060), False, 'import numpy\n'), ((6398, 6435), 'numpy.full', 'numpy.full', (['close_matrix.shape', '(False)'], {}), '(close_matrix.shape, False)\n', (6408, 6435), False, 'import numpy\n'), ((7065, 7086), 'tokiotest.generate_timeseries', 'generate_timeseries', ([], {}), '()\n', (7084, 7086), False, 'from tokiotest import generate_timeseries, compare_timeseries\n'), ((1634, 1680), 'numpy.random.random', 'numpy.random.random', ([], {'size': '(num_rows, num_cols)'}), '(size=(num_rows, num_cols))\n', (1653, 1680), False, 'import numpy\n'), ((1709, 1748), 'numpy.random.random', 'numpy.random.random', ([], {'size': '(1, num_cols)'}), '(size=(1, num_cols))\n', (1728, 1748), False, 'import numpy\n'), ((4956, 4994), 'numpy.isclose', 'numpy.isclose', (['calculated', 'total_delta'], {}), '(calculated, total_delta)\n', (4969, 4994), False, 'import numpy\n'), ((2021, 2061), 'numpy.vstack', 'numpy.vstack', (['(first_row, actual_deltas)'], {}), '((first_row, actual_deltas))\n', (2033, 2061), False, 'import numpy\n'), ((5202, 5240), 'numpy.isclose', 'numpy.isclose', (['(truth - calculated)', '(0.0)'], {}), '(truth - calculated, 0.0)\n', (5215, 5240), False, 'import numpy\n'), ((5793, 5831), 'numpy.isclose', 'numpy.isclose', (['calculated', 'total_delta'], {}), '(calculated, total_delta)\n', (5806, 5831), False, 'import numpy\n'), ((5883, 5915), 'numpy.isclose', 'numpy.isclose', (['truth', 'calculated'], {}), '(truth, calculated)\n', (5896, 5915), False, 'import numpy\n'), ((450, 484), 'datetime.datetime.fromtimestamp', 'datetime.datetime.fromtimestamp', (['x'], {}), '(x)\n', (481, 484), False, 'import datetime\n'), ((2792, 2825), 'numpy.random.randint', 'numpy.random.randint', (['(0)', 'num_rows'], {}), '(0, num_rows)\n', (2812, 2825), False, 'import numpy\n'), ((2827, 2853), 'numpy.random.randint', 'numpy.random.randint', (['(4)', '(8)'], {}), '(4, 8)\n', (2847, 2853), False, 'import numpy\n'), ((2982, 3015), 'numpy.random.randint', 'numpy.random.randint', (['(0)', 'num_rows'], {}), '(0, num_rows)\n', (3002, 3015), False, 'import numpy\n'), ((3017, 3044), 'numpy.random.randint', 'numpy.random.randint', (['(8)', '(12)'], {}), '(8, 12)\n', (3037, 3044), False, 'import numpy\n'), ((4728, 4791), 'numpy.matrix', 'numpy.matrix', (['[x for x in monotonic_values[:, icol] if x > 0.0]'], {}), '([x for x in monotonic_values[:, icol] if x > 0.0])\n', (4740, 4791), False, 'import numpy\n'), ((5565, 5628), 'numpy.matrix', 'numpy.matrix', (['[x for x in monotonic_values[:, icol] if x > 0.0]'], {}), '([x for x in monotonic_values[:, icol] if x > 0.0])\n', (5577, 5628), False, 'import numpy\n')] |
# -*- coding: utf-8 -*-
"""
Created on Thu Mar 02 15:59:36 2017
@author: <NAME>, <NAME>
"""
import math
import numpy as np
import h5py
import inspect
import dis
from sklearn.model_selection import KFold
import os
from GUI.PyQt.DLArt_GUI import dlart
import keras.backend as K
def expecting():
"""Return how many values the caller is expecting"""
f = inspect.currentframe()
f = f.f_back.f_back
c = f.f_code
i = f.f_lasti
bytecode = c.co_code
instruction = bytecode[i+3]
if instruction == dis.opmap['UNPACK_SEQUENCE']:
howmany = bytecode[i+4]
return howmany
elif instruction == dis.opmap['POP_TOP']:
return 0
return 1
def fSplitDataset(allPatches, allY, allPats, sSplitting, patchSize, patchOverlap, testTrainingDatasetRatio=0, validationTrainRatio=0, outPutPath=None, nfolds = 0, isRandomShuffle=True):
# TODO: adapt path
iReturn = expecting()
#iReturn = 1000
# 2D or 3D patching?
if len(patchSize) == 2:
#2D patches are used
if allPatches.shape[0] == patchSize[0] and allPatches.shape[1] == patchSize[1]:
allPatches = np.transpose(allPatches, (2, 0, 1))
elif len(patchSize) == 3:
#3D patches are used
if allPatches.shape[0] == patchSize[0] and allPatches.shape[1] == patchSize[1] and allPatches.shape[2] == patchSize[2]:
allPatches = np.transpose(allPatches, (3, 0, 1, 2))
if sSplitting == dlart.DeepLearningArtApp.SIMPLE_RANDOM_SAMPLE_SPLITTING:
# splitting
indexSlices = range(allPatches.shape[0])
if isRandomShuffle:
indexSlices = np.random.permutation(indexSlices)
if len(patchSize)==2:
#2D patching
allPatches = allPatches[indexSlices, :, :]
elif len(patchSize)==3:
#3D patching
allPatches = allPatches[indexSlices, :, :, :]
shapeAllY = allY.shape
if len(shapeAllY) > 1:
if allY.shape[0] == patchSize[0] and allY.shape[1] == patchSize[1]:
allY = np.transpose(allY, (2, 0, 1))
allY = allY[indexSlices]
#num of samples in test set and validation set
numAllPatches = allPatches.shape[0]
numSamplesTest = math.floor(testTrainingDatasetRatio*numAllPatches)
numSamplesValidation = math.floor(validationTrainRatio*(numAllPatches-numSamplesTest))
if len(patchSize) == 2:
#2D patching
# subarrays as no-copy views (array slices)
X_test = allPatches[:numSamplesTest, :, :]
X_valid = allPatches[numSamplesTest:(numSamplesTest+numSamplesValidation), :, :]
X_train = allPatches[(numSamplesTest+numSamplesValidation):, :, :]
elif len(patchSize) == 3:
# 3D patching
# subarrays as no-copy views (array slices)
X_test = allPatches[:numSamplesTest, :, :, :]
X_valid = allPatches[numSamplesTest:(numSamplesTest + numSamplesValidation), :, :, :]
X_train = allPatches[(numSamplesTest + numSamplesValidation):, :, :, :]
y_test = allY[:numSamplesTest]
y_valid = allY[numSamplesTest:(numSamplesTest + numSamplesValidation)]
y_train = allY[(numSamplesTest + numSamplesValidation):]
# #random samples
# nPatches = allPatches.shape[0]
# dVal = math.floor(split_ratio * nPatches)
# rand_num = np.random.permutation(np.arange(nPatches))
# rand_num = rand_num[0:int(dVal)].astype(int)
# print(rand_num)
#
# #do splitting
# X_test = allPatches[rand_num, :, :]
# y_test = allY[rand_num]
# X_train = allPatches
# X_train = np.delete(X_train, rand_num, axis=0)
# y_train = allY
# y_train = np.delete(y_train, rand_num)
# print(X_train.shape)
# print(X_test.shape)
# print(y_train.shape)
# print(y_test.shape)
# #!!!! train dataset is not randomly shuffeled!!!
if iReturn == 0:
if len(patchSize) == 3:
folder = sFolder + os.sep + str(patchSize[0]) + str(patchSize[1]) + str(patchSize[2])
Path = sFolder + os.sep + str(patchSize[0]) + str(patchSize[1]) + str(
patchSize[2]) + os.sep + 'normal_' + str(patchSize[0]) + str(patchSize[1]) + '.h5'
else:
folder = sFolder + os.sep + str(patchSize[0]) + str(patchSize[1])
Path = sFolder + os.sep + str(patchSize[0]) + str(patchSize[1]) + os.sep + 'normal_' + str(
patchSize[0]) + str(patchSize[1]) + '.h5'
if os.path.isdir(folder):
pass
else:
os.makedirs(folder)
print(Path)
with h5py.File(Path, 'w') as hf:
hf.create_dataset('X_train', data=X_train)
hf.create_dataset('X_test', data=X_test)
hf.create_dataset('y_train', data=y_train)
hf.create_dataset('y_test', data=y_test)
hf.create_dataset('patchSize', data=patchSize)
hf.create_dataset('patchOverlap', data=patchOverlap)
else:
# if len(patchSize) == 2:
# # 2D patches are used
# if allPatches.shape[1] == patchSize[0] and allPatches.shape[2] == patchSize[1]:
# X_train = np.transpose(X_train, (1, 2, 0))
# X_valid = np.transpose(X_valid, (1, 2, 0))
# X_test = np.transpose(X_test, (1, 2, 0))
# elif len(patchSize) == 3:
# # 3D patches are used
# if allPatches.shape[0] == patchSize[0] and allPatches.shape[1] == patchSize[1] and allPatches.shape[2] == patchSize[2]:
# X_train = np.transpose(X_train, (1, 2, 3, 0))
# X_valid = np.transpose(X_valid, (1, 2, 3, 0))
# X_test = np.transpose(X_test, (1, 2, 3, 0))
return [X_train], [y_train], [X_valid], [y_valid], [X_test], [y_test] # embed in a 1-fold list
elif sSplitting == dlart.DeepLearningArtApp.CROSS_VALIDATION_SPLITTING:
# split into test/train sets
#shuffle
indexSlices = range(allPatches.shape[0])
indexSlices = np.random.permutation(indexSlices)
allPatches = allPatches[indexSlices, :, :]
allY = allY[indexSlices]
# num of samples in test set
numAllPatches = allPatches.shape[0]
numSamplesTest = math.floor(testTrainingDatasetRatio*numAllPatches)
# subarrays as no-copy views (array slices)
xTest = allPatches[:numSamplesTest, :, :]
yTest = allY[:numSamplesTest]
xTrain = allPatches[numSamplesTest:, :, :]
yTrain = allY[numSamplesTest:]
# split training dataset into n folds
if nfolds == 0:
kf = KFold(n_splits=len(allPats))
else:
kf = KFold(n_splits=nfolds)
#ind_split = 0
X_trainFold = []
X_testFold = []
y_trainFold = []
y_testFold = []
for train_index, test_index in kf.split(xTrain):
X_train, X_test = xTrain[train_index], xTrain[test_index]
y_train, y_test = yTrain[train_index], yTrain[test_index]
if iReturn == 0:
if len(patchSize) == 3:
folder = sFolder + os.sep + str(patchSize[0]) + str(patchSize[1]) + str(patchSize[2])
Path = sFolder + os.sep + str(patchSize[0]) + str(patchSize[1]) + str(
patchSize[2]) + os.sep + 'crossVal_data' + str(ind_split) + '_' + str(patchSize[0]) + str(
patchSize[1]) + str(patchSize[2]) + '.h5'
else:
folder = sFolder + os.sep + str(patchSize[0]) + str(patchSize[1])
Path = sFolder + os.sep + str(patchSize[0]) + str(patchSize[1]) + os.sep + 'crossVal_data' + str(
ind_split) + '_' + str(patchSize[0]) + str(patchSize[1]) + '.h5'
if os.path.isdir(folder):
pass
else:
os.makedirs(folder)
with h5py.File(Path, 'w') as hf:
hf.create_dataset('X_train', data=X_train)
hf.create_dataset('X_test', data=X_test)
hf.create_dataset('y_train', data=y_train)
hf.create_dataset('y_test', data=y_test)
hf.create_dataset('patchSize', data=patchSize)
hf.create_dataset('patchOverlap', data=patchOverlap)
else:
X_trainFold.append(X_train)
X_testFold.append(X_test)
y_trainFold.append(y_train)
y_testFold.append(y_test)
#ind_split += 1
X_trainFold = np.asarray(X_trainFold)
X_testFold = np.asarray(X_testFold)
y_trainFold = np.asarray(y_trainFold)
y_testFold = np.asarray(y_testFold)
if iReturn > 0:
return X_trainFold, y_trainFold, X_testFold, y_testFold, xTest, yTest
elif sSplitting == dlart.DeepLearningArtApp.PATIENT_CROSS_VALIDATION_SPLITTING:
unique_pats = len(allPats)
X_trainFold = []
X_testFold = []
y_trainFold = []
y_testFold = []
for ind_split in unique_pats:
train_index = np.where(allPats != ind_split)[0]
test_index = np.where(allPats == ind_split)[0]
X_train, X_test = allPatches[train_index], allPatches[test_index]
y_train, y_test = allY[train_index], allY[test_index]
if iReturn == 0:
if len(patchSize) == 3:
folder = sFolder + os.sep + str(patchSize[0]) + str(patchSize[1]) + str(patchSize[2])
Path = sFolder + os.sep + str(patchSize[0]) + str(patchSize[1]) + str(
patchSize[2]) + os.sep + 'crossVal' + str(ind_split) + '_' + str(patchSize[0]) + str(
patchSize[1]) + str(patchSize[2]) + '.h5'
else:
folder = sFolder + os.sep + str(patchSize[0]) + str(patchSize[1])
Path = sFolder + os.sep + str(patchSize[0]) + str(patchSize[1]) + os.sep + 'crossVal' + str(
ind_split) + '_' + str(patchSize[0]) + str(patchSize[1]) + '.h5'
if os.path.isdir(folder):
pass
else:
os.makedirs(folder)
with h5py.File(Path, 'w') as hf:
hf.create_dataset('X_train', data=X_train)
hf.create_dataset('X_test', data=X_test)
hf.create_dataset('y_train', data=y_train)
hf.create_dataset('y_test', data=y_test)
hf.create_dataset('patchSize', data=patchSize)
hf.create_dataset('patchOverlap', data=patchOverlap)
else:
X_trainFold.append(X_train)
X_testFold.append(X_test)
y_trainFold.append(y_train)
y_testFold.append(y_test)
X_trainFold = np.asarray(X_trainFold, dtype='f')
X_testFold = np.asarray(X_testFold, dtype='f')
y_trainFold = np.asarray(y_trainFold, dtype='f')
y_testFold = np.asarray(y_testFold, dtype='f')
if iReturn > 0:
return X_trainFold, y_trainFold, X_testFold, y_testFold
elif sSplitting == "normal":
print("Done")
nPatches = allPatches.shape[0]
dVal = math.floor(split_ratio * nPatches)
rand_num = np.random.permutation(np.arange(nPatches))
rand_num = rand_num[0:int(dVal)].astype(int)
print(rand_num)
if len(patchSize) == 3:
X_test = allPatches[rand_num, :, :, :]
else:
X_test = allPatches[rand_num, :, :]
y_test = allY[rand_num]
X_train = allPatches
X_train = np.delete(X_train, rand_num, axis=0)
y_train = allY
y_train = np.delete(y_train, rand_num)
#print(X_train.shape)
#print(X_test.shape)
#print(y_train.shape)
#print(y_test.shape)
if iReturn == 0:
if len(patchSize) == 3:
folder = sFolder + os.sep + str(patchSize[0]) + str(patchSize[1]) + str(patchSize[2])
Path = sFolder + os.sep + str(patchSize[0]) + str(patchSize[1]) + str(patchSize[2]) + os.sep + 'normal_' + str(patchSize[0]) + str(patchSize[1]) + '.h5'
else:
folder = sFolder + os.sep + str(patchSize[0]) + str(patchSize[1])
Path = sFolder + os.sep + str(patchSize[0]) + str(patchSize[1]) + os.sep + 'normal_' + str(patchSize[0]) + str(patchSize[1]) + '.h5'
if os.path.isdir(folder):
pass
else:
os.makedirs(folder)
print(Path)
with h5py.File(Path, 'w') as hf:
hf.create_dataset('X_train', data=X_train)
hf.create_dataset('X_test', data=X_test)
hf.create_dataset('y_train', data=y_train)
hf.create_dataset('y_test', data=y_test)
hf.create_dataset('patchSize', data=patchSize)
hf.create_dataset('patchOverlap', data=patchOverlap)
else:
return [X_train], [y_train], [X_test], [y_test] # embed in a 1-fold list
elif sSplitting == "crossvalidation_data":
if nfolds == 0:
kf = KFold(n_splits=len(np.unique(allPats)))
else:
kf = KFold(n_splits=nfolds)
ind_split = 0
X_trainFold = []
X_testFold = []
y_trainFold = []
y_testFold = []
for train_index, test_index in kf.split(allPatches):
X_train, X_test = allPatches[train_index], allPatches[test_index]
y_train, y_test = allY[train_index], allY[test_index]
if iReturn == 0:
if len(patchSize) == 3:
folder = sFolder + os.sep + str(patchSize[0]) + str(patchSize[1]) + str(patchSize[2])
Path = sFolder + os.sep + str(patchSize[0]) + str(patchSize[1]) + str(patchSize[2]) + os.sep + 'crossVal_data' + str(ind_split) + '_' + str(patchSize[0]) + str(patchSize[1]) + str(patchSize[2])+ '.h5'
else:
folder = sFolder + os.sep + str(patchSize[0]) + str(patchSize[1])
Path = sFolder + os.sep + str(patchSize[0]) + str(patchSize[1]) + os.sep + 'crossVal_data' + str(ind_split) + '_' + str(patchSize[0]) + str(patchSize[1]) + '.h5'
if os.path.isdir(folder):
pass
else:
os.makedirs(folder)
with h5py.File(Path, 'w') as hf:
hf.create_dataset('X_train', data=X_train)
hf.create_dataset('X_test', data=X_test)
hf.create_dataset('y_train', data=y_train)
hf.create_dataset('y_test', data=y_test)
hf.create_dataset('patchSize', data=patchSize)
hf.create_dataset('patchOverlap', data=patchOverlap)
else:
X_trainFold.append(X_train)
X_testFold.append(X_test)
y_trainFold.append(y_train)
y_testFold.append(y_test)
ind_split += 1
X_trainFold = np.asarray(X_trainFold)
X_testFold = np.asarray(X_testFold)
y_trainFold = np.asarray(y_trainFold)
y_testFold = np.asarray(y_testFold)
if iReturn > 0:
return X_trainFold, y_trainFold, X_testFold, y_testFold
elif sSplitting == "crossvalidation_patient":
unique_pats = np.unique(allPats)
X_trainFold = []
X_testFold = []
y_trainFold = []
y_testFold = []
for ind_split in unique_pats:
train_index = np.where(allPats != ind_split)[0]
test_index = np.where(allPats == ind_split)[0]
X_train, X_test = allPatches[train_index], allPatches[test_index]
y_train, y_test = allY[train_index], allY[test_index]
if iReturn == 0:
if len(patchSize) == 3:
folder = sFolder + os.sep + str(patchSize[0]) + str(patchSize[1]) + str(patchSize[2])
Path = sFolder + os.sep + str(patchSize[0]) + str(patchSize[1]) + str(patchSize[2]) + os.sep + 'crossVal' + str(ind_split) + '_' + str(patchSize[0]) + str(patchSize[1]) + str(patchSize[2])+ '.h5'
else:
folder = sFolder + os.sep + str(patchSize[0]) + str(patchSize[1])
Path = sFolder + os.sep + str(patchSize[0]) + str(patchSize[1]) + os.sep + 'crossVal' + str(
ind_split) + '_' + str(patchSize[0]) + str(patchSize[1]) + '.h5'
if os.path.isdir(folder):
pass
else:
os.makedirs(folder)
with h5py.File(Path, 'w') as hf:
hf.create_dataset('X_train', data=X_train)
hf.create_dataset('X_test', data=X_test)
hf.create_dataset('y_train', data=y_train)
hf.create_dataset('y_test', data=y_test)
hf.create_dataset('patchSize', data=patchSize)
hf.create_dataset('patchOverlap', data=patchOverlap)
else:
X_trainFold.append(X_train)
X_testFold.append(X_test)
y_trainFold.append(y_train)
y_testFold.append(y_test)
X_trainFold = np.asarray(X_trainFold, dtype='f')
X_testFold = np.asarray(X_testFold, dtype='f')
y_trainFold = np.asarray(y_trainFold, dtype='f')
y_testFold = np.asarray(y_testFold, dtype='f')
if iReturn > 0:
return X_trainFold, y_trainFold, X_testFold, y_testFold
def fSplitSegmentationDataset(allPatches, allY, allSegmentationMasks, allPats, sSplitting, patchSize, patchOverlap, testTrainingDatasetRatio=0, validationTrainRatio=0, outPutPath=None, nfolds = 0, isRandomShuffle=True):
# TODO: adapt path
iReturn = expecting()
#iReturn = 1000
# 2D or 3D patching?
if len(patchSize) == 2:
#2D patches are used
if allPatches.shape[0] == patchSize[0] and allPatches.shape[1] == patchSize[1]:
allPatches = np.transpose(allPatches, (2, 0, 1))
allSegmentationMasks = np.transpose(allSegmentationMasks, (2, 0, 1))
elif len(patchSize) == 3:
#3D patches are used
if allPatches.shape[0] == patchSize[0] and allPatches.shape[1] == patchSize[1] and allPatches.shape[2] == patchSize[2]:
allPatches = np.transpose(allPatches, (3, 0, 1, 2))
allSegmentationMasks = np.transpose(allSegmentationMasks, (3, 0, 1, 2))
if sSplitting == dlart.DeepLearningArtApp.SIMPLE_RANDOM_SAMPLE_SPLITTING:
# splitting
indexSlices = range(allPatches.shape[0])
if isRandomShuffle:
indexSlices = np.random.permutation(indexSlices)
if len(patchSize)==2:
#2D patching
allPatches = allPatches[indexSlices, :, :]
allSegmentationMasks = allSegmentationMasks[indexSlices, :, :]
elif len(patchSize)==3:
#3D patching
allPatches = allPatches[indexSlices, :, :, :]
allSegmentationMasks = allSegmentationMasks[indexSlices, :, :, :]
shapeAllY = allY.shape
if len(shapeAllY) > 1:
if allY.shape[0] == patchSize[0] and allY.shape[1] == patchSize[1]:
allY = np.transpose(allY, (2, 0, 1))
allY = allY[indexSlices]
#num of samples in test set and validation set
numAllPatches = allPatches.shape[0]
numSamplesTest = math.floor(testTrainingDatasetRatio*numAllPatches)
numSamplesValidation = math.floor(validationTrainRatio*(numAllPatches-numSamplesTest))
if len(patchSize) == 2:
#2D patching
# subarrays as no-copy views (array slices)
X_test = allPatches[:numSamplesTest, :, :]
Y_segMasks_test = allSegmentationMasks[:numSamplesTest, :, :]
X_valid = allPatches[numSamplesTest:(numSamplesTest+numSamplesValidation), :, :]
Y_segMasks_valid = allSegmentationMasks[numSamplesTest:(numSamplesTest+numSamplesValidation), :, :]
X_train = allPatches[(numSamplesTest+numSamplesValidation):, :, :]
Y_segMasks_train = allSegmentationMasks[(numSamplesTest+numSamplesValidation):, :, :]
elif len(patchSize) == 3:
# 3D patching
# subarrays as no-copy views (array slices)
X_test = allPatches[:numSamplesTest, :, :, :]
Y_segMasks_test = allSegmentationMasks[:numSamplesTest, :, :, :]
X_valid = allPatches[numSamplesTest:(numSamplesTest + numSamplesValidation), :, :, :]
Y_segMasks_valid = allSegmentationMasks[numSamplesTest:(numSamplesTest + numSamplesValidation), :, :, :]
X_train = allPatches[(numSamplesTest + numSamplesValidation):, :, :, :]
Y_segMasks_train = allSegmentationMasks[(numSamplesTest + numSamplesValidation):, :, :, :]
y_test = allY[:numSamplesTest]
y_valid = allY[numSamplesTest:(numSamplesTest + numSamplesValidation)]
y_train = allY[(numSamplesTest + numSamplesValidation):]
# #random samples
# nPatches = allPatches.shape[0]
# dVal = math.floor(split_ratio * nPatches)
# rand_num = np.random.permutation(np.arange(nPatches))
# rand_num = rand_num[0:int(dVal)].astype(int)
# print(rand_num)
#
# #do splitting
# X_test = allPatches[rand_num, :, :]
# y_test = allY[rand_num]
# X_train = allPatches
# X_train = np.delete(X_train, rand_num, axis=0)
# y_train = allY
# y_train = np.delete(y_train, rand_num)
# print(X_train.shape)
# print(X_test.shape)
# print(y_train.shape)
# print(y_test.shape)
# #!!!! train dataset is not randomly shuffeled!!!
if iReturn == 0:
if len(patchSize) == 3:
folder = sFolder + os.sep + str(patchSize[0]) + str(patchSize[1]) + str(patchSize[2])
Path = sFolder + os.sep + str(patchSize[0]) + str(patchSize[1]) + str(
patchSize[2]) + os.sep + 'normal_' + str(patchSize[0]) + str(patchSize[1]) + '.h5'
else:
folder = sFolder + os.sep + str(patchSize[0]) + str(patchSize[1])
Path = sFolder + os.sep + str(patchSize[0]) + str(patchSize[1]) + os.sep + 'normal_' + str(
patchSize[0]) + str(patchSize[1]) + '.h5'
if os.path.isdir(folder):
pass
else:
os.makedirs(folder)
print(Path)
with h5py.File(Path, 'w') as hf:
hf.create_dataset('X_train', data=X_train)
hf.create_dataset('X_test', data=X_test)
hf.create_dataset('y_train', data=y_train)
hf.create_dataset('y_test', data=y_test)
hf.create_dataset('patchSize', data=patchSize)
hf.create_dataset('patchOverlap', data=patchOverlap)
else:
# if len(patchSize) == 2:
# # 2D patches are used
# if allPatches.shape[1] == patchSize[0] and allPatches.shape[2] == patchSize[1]:
# X_train = np.transpose(X_train, (1, 2, 0))
# X_valid = np.transpose(X_valid, (1, 2, 0))
# X_test = np.transpose(X_test, (1, 2, 0))
# elif len(patchSize) == 3:
# # 3D patches are used
# if allPatches.shape[0] == patchSize[0] and allPatches.shape[1] == patchSize[1] and allPatches.shape[2] == patchSize[2]:
# X_train = np.transpose(X_train, (1, 2, 3, 0))
# X_valid = np.transpose(X_valid, (1, 2, 3, 0))
# X_test = np.transpose(X_test, (1, 2, 3, 0))
return [X_train], [y_train], [Y_segMasks_train], [X_valid], [y_valid], [Y_segMasks_valid], [X_test], [y_test], [Y_segMasks_test] # embed in a 1-fold list
elif sSplitting == dlart.DeepLearningArtApp.CROSS_VALIDATION_SPLITTING:
# split into test/train sets
#shuffle
indexSlices = range(allPatches.shape[0])
indexSlices = np.random.permutation(indexSlices)
allPatches = allPatches[indexSlices, :, :]
allY = allY[indexSlices]
# num of samples in test set
numAllPatches = allPatches.shape[0]
numSamplesTest = math.floor(testTrainingDatasetRatio*numAllPatches)
# subarrays as no-copy views (array slices)
xTest = allPatches[:numSamplesTest, :, :]
yTest = allY[:numSamplesTest]
xTrain = allPatches[numSamplesTest:, :, :]
yTrain = allY[numSamplesTest:]
# split training dataset into n folds
if nfolds == 0:
kf = KFold(n_splits=len(allPats))
else:
kf = KFold(n_splits=nfolds)
#ind_split = 0
X_trainFold = []
X_testFold = []
y_trainFold = []
y_testFold = []
for train_index, test_index in kf.split(xTrain):
X_train, X_test = xTrain[train_index], xTrain[test_index]
y_train, y_test = yTrain[train_index], yTrain[test_index]
if iReturn == 0:
if len(patchSize) == 3:
folder = sFolder + os.sep + str(patchSize[0]) + str(patchSize[1]) + str(patchSize[2])
Path = sFolder + os.sep + str(patchSize[0]) + str(patchSize[1]) + str(
patchSize[2]) + os.sep + 'crossVal_data' + str(ind_split) + '_' + str(patchSize[0]) + str(
patchSize[1]) + str(patchSize[2]) + '.h5'
else:
folder = sFolder + os.sep + str(patchSize[0]) + str(patchSize[1])
Path = sFolder + os.sep + str(patchSize[0]) + str(patchSize[1]) + os.sep + 'crossVal_data' + str(
ind_split) + '_' + str(patchSize[0]) + str(patchSize[1]) + '.h5'
if os.path.isdir(folder):
pass
else:
os.makedirs(folder)
with h5py.File(Path, 'w') as hf:
hf.create_dataset('X_train', data=X_train)
hf.create_dataset('X_test', data=X_test)
hf.create_dataset('y_train', data=y_train)
hf.create_dataset('y_test', data=y_test)
hf.create_dataset('patchSize', data=patchSize)
hf.create_dataset('patchOverlap', data=patchOverlap)
else:
X_trainFold.append(X_train)
X_testFold.append(X_test)
y_trainFold.append(y_train)
y_testFold.append(y_test)
#ind_split += 1
X_trainFold = np.asarray(X_trainFold)
X_testFold = np.asarray(X_testFold)
y_trainFold = np.asarray(y_trainFold)
y_testFold = np.asarray(y_testFold)
if iReturn > 0:
return X_trainFold, y_trainFold, X_testFold, y_testFold, xTest, yTest
elif sSplitting == dlart.DeepLearningArtApp.PATIENT_CROSS_VALIDATION_SPLITTING:
unique_pats = len(allPats)
X_trainFold = []
X_testFold = []
y_trainFold = []
y_testFold = []
for ind_split in unique_pats:
train_index = np.where(allPats != ind_split)[0]
test_index = np.where(allPats == ind_split)[0]
X_train, X_test = allPatches[train_index], allPatches[test_index]
y_train, y_test = allY[train_index], allY[test_index]
if iReturn == 0:
if len(patchSize) == 3:
folder = sFolder + os.sep + str(patchSize[0]) + str(patchSize[1]) + str(patchSize[2])
Path = sFolder + os.sep + str(patchSize[0]) + str(patchSize[1]) + str(
patchSize[2]) + os.sep + 'crossVal' + str(ind_split) + '_' + str(patchSize[0]) + str(
patchSize[1]) + str(patchSize[2]) + '.h5'
else:
folder = sFolder + os.sep + str(patchSize[0]) + str(patchSize[1])
Path = sFolder + os.sep + str(patchSize[0]) + str(patchSize[1]) + os.sep + 'crossVal' + str(
ind_split) + '_' + str(patchSize[0]) + str(patchSize[1]) + '.h5'
if os.path.isdir(folder):
pass
else:
os.makedirs(folder)
with h5py.File(Path, 'w') as hf:
hf.create_dataset('X_train', data=X_train)
hf.create_dataset('X_test', data=X_test)
hf.create_dataset('y_train', data=y_train)
hf.create_dataset('y_test', data=y_test)
hf.create_dataset('patchSize', data=patchSize)
hf.create_dataset('patchOverlap', data=patchOverlap)
else:
X_trainFold.append(X_train)
X_testFold.append(X_test)
y_trainFold.append(y_train)
y_testFold.append(y_test)
X_trainFold = np.asarray(X_trainFold, dtype='f')
X_testFold = np.asarray(X_testFold, dtype='f')
y_trainFold = np.asarray(y_trainFold, dtype='f')
y_testFold = np.asarray(y_testFold, dtype='f')
if iReturn > 0:
return X_trainFold, y_trainFold, X_testFold, y_testFold
def fSplitDatasetCorrection(sSplitting, dRefPatches, dArtPatches, allPats, split_ratio, nfolds, test_index):
"""
Split dataset with three options:
1. normal: randomly split data according to the split_ratio without cross validation
2. crossvalidation_data: perform crossvalidation with mixed patient data
3. crossvalidation_patient: perform crossvalidation with separate patient data
@param sSplitting: splitting mode 'normal', 'crossvalidation_data' or 'crossvalidation_patient'
@param dRefPatches: reference patches
@param dArtPatches: artifact patches
@param allPats: patient index
@param split_ratio: the ratio to split test data
@param nfolds: folds for cross validation
@return: testing and training data for both reference and artifact images
"""
train_ref_fold = []
test_ref_fold = []
train_art_fold = []
test_art_fold = []
# normal splitting
if sSplitting == 'normal':
nPatches = dRefPatches.shape[0]
dVal = math.floor(split_ratio * nPatches)
rand_num = np.random.permutation(np.arange(nPatches))
rand_num = rand_num[0:int(dVal)].astype(int)
test_ref_fold.append(dRefPatches[rand_num, :, :])
train_ref_fold.append(np.delete(dRefPatches, rand_num, axis=0))
test_art_fold.append(dArtPatches[rand_num, :, :])
train_art_fold.append(np.delete(dArtPatches, rand_num, axis=0))
# crossvalidation with mixed patient
if sSplitting == "crossvalidation_data":
if nfolds == 0:
kf = KFold(n_splits=len(np.unique(allPats)))
else:
kf = KFold(n_splits=nfolds)
for train_index, test_index in kf.split(dRefPatches):
train_ref, test_ref = dRefPatches[train_index], dRefPatches[test_index]
train_art, test_art = dArtPatches[train_index], dArtPatches[test_index]
train_ref_fold.append(train_ref)
train_art_fold.append(train_art)
test_ref_fold.append(test_ref)
test_art_fold.append(test_art)
# crossvalidation with separate patient
elif sSplitting == 'crossvalidation_patient':
if test_index == -1:
unique_pats = np.unique(allPats)
else:
unique_pats = [test_index]
for ind_split in unique_pats:
train_index = np.where(allPats != ind_split)[0]
test_index = np.where(allPats == ind_split)[0]
train_ref, test_ref = dRefPatches[train_index], dRefPatches[test_index]
train_art, test_art = dArtPatches[train_index], dArtPatches[test_index]
train_ref_fold.append(train_ref)
train_art_fold.append(train_art)
test_ref_fold.append(test_ref)
test_art_fold.append(test_art)
train_ref_fold = np.asarray(train_ref_fold, dtype='f')
train_art_fold = np.asarray(train_art_fold, dtype='f')
test_ref_fold = np.asarray(test_ref_fold, dtype='f')
test_art_fold = np.asarray(test_art_fold, dtype='f')
return train_ref_fold, test_ref_fold, train_art_fold, test_art_fold
| [
"h5py.File",
"os.makedirs",
"os.path.isdir",
"numpy.asarray",
"math.floor",
"numpy.transpose",
"sklearn.model_selection.KFold",
"numpy.where",
"numpy.arange",
"inspect.currentframe",
"numpy.random.permutation",
"numpy.delete",
"numpy.unique"
] | [((361, 383), 'inspect.currentframe', 'inspect.currentframe', ([], {}), '()\n', (381, 383), False, 'import inspect\n'), ((32536, 32573), 'numpy.asarray', 'np.asarray', (['train_ref_fold'], {'dtype': '"""f"""'}), "(train_ref_fold, dtype='f')\n", (32546, 32573), True, 'import numpy as np\n'), ((32595, 32632), 'numpy.asarray', 'np.asarray', (['train_art_fold'], {'dtype': '"""f"""'}), "(train_art_fold, dtype='f')\n", (32605, 32632), True, 'import numpy as np\n'), ((32653, 32689), 'numpy.asarray', 'np.asarray', (['test_ref_fold'], {'dtype': '"""f"""'}), "(test_ref_fold, dtype='f')\n", (32663, 32689), True, 'import numpy as np\n'), ((32710, 32746), 'numpy.asarray', 'np.asarray', (['test_art_fold'], {'dtype': '"""f"""'}), "(test_art_fold, dtype='f')\n", (32720, 32746), True, 'import numpy as np\n'), ((2243, 2295), 'math.floor', 'math.floor', (['(testTrainingDatasetRatio * numAllPatches)'], {}), '(testTrainingDatasetRatio * numAllPatches)\n', (2253, 2295), False, 'import math\n'), ((2325, 2392), 'math.floor', 'math.floor', (['(validationTrainRatio * (numAllPatches - numSamplesTest))'], {}), '(validationTrainRatio * (numAllPatches - numSamplesTest))\n', (2335, 2392), False, 'import math\n'), ((19866, 19918), 'math.floor', 'math.floor', (['(testTrainingDatasetRatio * numAllPatches)'], {}), '(testTrainingDatasetRatio * numAllPatches)\n', (19876, 19918), False, 'import math\n'), ((19948, 20015), 'math.floor', 'math.floor', (['(validationTrainRatio * (numAllPatches - numSamplesTest))'], {}), '(validationTrainRatio * (numAllPatches - numSamplesTest))\n', (19958, 20015), False, 'import math\n'), ((30749, 30783), 'math.floor', 'math.floor', (['(split_ratio * nPatches)'], {}), '(split_ratio * nPatches)\n', (30759, 30783), False, 'import math\n'), ((1135, 1170), 'numpy.transpose', 'np.transpose', (['allPatches', '(2, 0, 1)'], {}), '(allPatches, (2, 0, 1))\n', (1147, 1170), True, 'import numpy as np\n'), ((1625, 1659), 'numpy.random.permutation', 'np.random.permutation', (['indexSlices'], {}), '(indexSlices)\n', (1646, 1659), True, 'import numpy as np\n'), ((4633, 4654), 'os.path.isdir', 'os.path.isdir', (['folder'], {}), '(folder)\n', (4646, 4654), False, 'import os\n'), ((6278, 6312), 'numpy.random.permutation', 'np.random.permutation', (['indexSlices'], {}), '(indexSlices)\n', (6299, 6312), True, 'import numpy as np\n'), ((6505, 6557), 'math.floor', 'math.floor', (['(testTrainingDatasetRatio * numAllPatches)'], {}), '(testTrainingDatasetRatio * numAllPatches)\n', (6515, 6557), False, 'import math\n'), ((8851, 8874), 'numpy.asarray', 'np.asarray', (['X_trainFold'], {}), '(X_trainFold)\n', (8861, 8874), True, 'import numpy as np\n'), ((8896, 8918), 'numpy.asarray', 'np.asarray', (['X_testFold'], {}), '(X_testFold)\n', (8906, 8918), True, 'import numpy as np\n'), ((8941, 8964), 'numpy.asarray', 'np.asarray', (['y_trainFold'], {}), '(y_trainFold)\n', (8951, 8964), True, 'import numpy as np\n'), ((8986, 9008), 'numpy.asarray', 'np.asarray', (['y_testFold'], {}), '(y_testFold)\n', (8996, 9008), True, 'import numpy as np\n'), ((18440, 18475), 'numpy.transpose', 'np.transpose', (['allPatches', '(2, 0, 1)'], {}), '(allPatches, (2, 0, 1))\n', (18452, 18475), True, 'import numpy as np\n'), ((18511, 18556), 'numpy.transpose', 'np.transpose', (['allSegmentationMasks', '(2, 0, 1)'], {}), '(allSegmentationMasks, (2, 0, 1))\n', (18523, 18556), True, 'import numpy as np\n'), ((19095, 19129), 'numpy.random.permutation', 'np.random.permutation', (['indexSlices'], {}), '(indexSlices)\n', (19116, 19129), True, 'import numpy as np\n'), ((22842, 22863), 'os.path.isdir', 'os.path.isdir', (['folder'], {}), '(folder)\n', (22855, 22863), False, 'import os\n'), ((24547, 24581), 'numpy.random.permutation', 'np.random.permutation', (['indexSlices'], {}), '(indexSlices)\n', (24568, 24581), True, 'import numpy as np\n'), ((24774, 24826), 'math.floor', 'math.floor', (['(testTrainingDatasetRatio * numAllPatches)'], {}), '(testTrainingDatasetRatio * numAllPatches)\n', (24784, 24826), False, 'import math\n'), ((27120, 27143), 'numpy.asarray', 'np.asarray', (['X_trainFold'], {}), '(X_trainFold)\n', (27130, 27143), True, 'import numpy as np\n'), ((27165, 27187), 'numpy.asarray', 'np.asarray', (['X_testFold'], {}), '(X_testFold)\n', (27175, 27187), True, 'import numpy as np\n'), ((27210, 27233), 'numpy.asarray', 'np.asarray', (['y_trainFold'], {}), '(y_trainFold)\n', (27220, 27233), True, 'import numpy as np\n'), ((27255, 27277), 'numpy.asarray', 'np.asarray', (['y_testFold'], {}), '(y_testFold)\n', (27265, 27277), True, 'import numpy as np\n'), ((30825, 30844), 'numpy.arange', 'np.arange', (['nPatches'], {}), '(nPatches)\n', (30834, 30844), True, 'import numpy as np\n'), ((30988, 31028), 'numpy.delete', 'np.delete', (['dRefPatches', 'rand_num'], {'axis': '(0)'}), '(dRefPatches, rand_num, axis=0)\n', (30997, 31028), True, 'import numpy as np\n'), ((31118, 31158), 'numpy.delete', 'np.delete', (['dArtPatches', 'rand_num'], {'axis': '(0)'}), '(dArtPatches, rand_num, axis=0)\n', (31127, 31158), True, 'import numpy as np\n'), ((31359, 31381), 'sklearn.model_selection.KFold', 'KFold', ([], {'n_splits': 'nfolds'}), '(n_splits=nfolds)\n', (31364, 31381), False, 'from sklearn.model_selection import KFold\n'), ((1383, 1421), 'numpy.transpose', 'np.transpose', (['allPatches', '(3, 0, 1, 2)'], {}), '(allPatches, (3, 0, 1, 2))\n', (1395, 1421), True, 'import numpy as np\n'), ((2053, 2082), 'numpy.transpose', 'np.transpose', (['allY', '(2, 0, 1)'], {}), '(allY, (2, 0, 1))\n', (2065, 2082), True, 'import numpy as np\n'), ((4711, 4730), 'os.makedirs', 'os.makedirs', (['folder'], {}), '(folder)\n', (4722, 4730), False, 'import os\n'), ((4773, 4793), 'h5py.File', 'h5py.File', (['Path', '"""w"""'], {}), "(Path, 'w')\n", (4782, 4793), False, 'import h5py\n'), ((6936, 6958), 'sklearn.model_selection.KFold', 'KFold', ([], {'n_splits': 'nfolds'}), '(n_splits=nfolds)\n', (6941, 6958), False, 'from sklearn.model_selection import KFold\n'), ((11174, 11208), 'numpy.asarray', 'np.asarray', (['X_trainFold'], {'dtype': '"""f"""'}), "(X_trainFold, dtype='f')\n", (11184, 11208), True, 'import numpy as np\n'), ((11230, 11263), 'numpy.asarray', 'np.asarray', (['X_testFold'], {'dtype': '"""f"""'}), "(X_testFold, dtype='f')\n", (11240, 11263), True, 'import numpy as np\n'), ((11286, 11320), 'numpy.asarray', 'np.asarray', (['y_trainFold'], {'dtype': '"""f"""'}), "(y_trainFold, dtype='f')\n", (11296, 11320), True, 'import numpy as np\n'), ((11342, 11375), 'numpy.asarray', 'np.asarray', (['y_testFold'], {'dtype': '"""f"""'}), "(y_testFold, dtype='f')\n", (11352, 11375), True, 'import numpy as np\n'), ((18769, 18807), 'numpy.transpose', 'np.transpose', (['allPatches', '(3, 0, 1, 2)'], {}), '(allPatches, (3, 0, 1, 2))\n', (18781, 18807), True, 'import numpy as np\n'), ((18843, 18891), 'numpy.transpose', 'np.transpose', (['allSegmentationMasks', '(3, 0, 1, 2)'], {}), '(allSegmentationMasks, (3, 0, 1, 2))\n', (18855, 18891), True, 'import numpy as np\n'), ((19676, 19705), 'numpy.transpose', 'np.transpose', (['allY', '(2, 0, 1)'], {}), '(allY, (2, 0, 1))\n', (19688, 19705), True, 'import numpy as np\n'), ((22920, 22939), 'os.makedirs', 'os.makedirs', (['folder'], {}), '(folder)\n', (22931, 22939), False, 'import os\n'), ((22982, 23002), 'h5py.File', 'h5py.File', (['Path', '"""w"""'], {}), "(Path, 'w')\n", (22991, 23002), False, 'import h5py\n'), ((25205, 25227), 'sklearn.model_selection.KFold', 'KFold', ([], {'n_splits': 'nfolds'}), '(n_splits=nfolds)\n', (25210, 25227), False, 'from sklearn.model_selection import KFold\n'), ((29443, 29477), 'numpy.asarray', 'np.asarray', (['X_trainFold'], {'dtype': '"""f"""'}), "(X_trainFold, dtype='f')\n", (29453, 29477), True, 'import numpy as np\n'), ((29499, 29532), 'numpy.asarray', 'np.asarray', (['X_testFold'], {'dtype': '"""f"""'}), "(X_testFold, dtype='f')\n", (29509, 29532), True, 'import numpy as np\n'), ((29555, 29589), 'numpy.asarray', 'np.asarray', (['y_trainFold'], {'dtype': '"""f"""'}), "(y_trainFold, dtype='f')\n", (29565, 29589), True, 'import numpy as np\n'), ((29611, 29644), 'numpy.asarray', 'np.asarray', (['y_testFold'], {'dtype': '"""f"""'}), "(y_testFold, dtype='f')\n", (29621, 29644), True, 'import numpy as np\n'), ((31940, 31958), 'numpy.unique', 'np.unique', (['allPats'], {}), '(allPats)\n', (31949, 31958), True, 'import numpy as np\n'), ((8061, 8082), 'os.path.isdir', 'os.path.isdir', (['folder'], {}), '(folder)\n', (8074, 8082), False, 'import os\n'), ((11579, 11613), 'math.floor', 'math.floor', (['(split_ratio * nPatches)'], {}), '(split_ratio * nPatches)\n', (11589, 11613), False, 'import math\n'), ((11977, 12013), 'numpy.delete', 'np.delete', (['X_train', 'rand_num'], {'axis': '(0)'}), '(X_train, rand_num, axis=0)\n', (11986, 12013), True, 'import numpy as np\n'), ((12055, 12083), 'numpy.delete', 'np.delete', (['y_train', 'rand_num'], {}), '(y_train, rand_num)\n', (12064, 12083), True, 'import numpy as np\n'), ((26330, 26351), 'os.path.isdir', 'os.path.isdir', (['folder'], {}), '(folder)\n', (26343, 26351), False, 'import os\n'), ((32076, 32106), 'numpy.where', 'np.where', (['(allPats != ind_split)'], {}), '(allPats != ind_split)\n', (32084, 32106), True, 'import numpy as np\n'), ((32135, 32165), 'numpy.where', 'np.where', (['(allPats == ind_split)'], {}), '(allPats == ind_split)\n', (32143, 32165), True, 'import numpy as np\n'), ((8151, 8170), 'os.makedirs', 'os.makedirs', (['folder'], {}), '(folder)\n', (8162, 8170), False, 'import os\n'), ((8193, 8213), 'h5py.File', 'h5py.File', (['Path', '"""w"""'], {}), "(Path, 'w')\n", (8202, 8213), False, 'import h5py\n'), ((9402, 9432), 'numpy.where', 'np.where', (['(allPats != ind_split)'], {}), '(allPats != ind_split)\n', (9410, 9432), True, 'import numpy as np\n'), ((9461, 9491), 'numpy.where', 'np.where', (['(allPats == ind_split)'], {}), '(allPats == ind_split)\n', (9469, 9491), True, 'import numpy as np\n'), ((10411, 10432), 'os.path.isdir', 'os.path.isdir', (['folder'], {}), '(folder)\n', (10424, 10432), False, 'import os\n'), ((11655, 11674), 'numpy.arange', 'np.arange', (['nPatches'], {}), '(nPatches)\n', (11664, 11674), True, 'import numpy as np\n'), ((12800, 12821), 'os.path.isdir', 'os.path.isdir', (['folder'], {}), '(folder)\n', (12813, 12821), False, 'import os\n'), ((15435, 15458), 'numpy.asarray', 'np.asarray', (['X_trainFold'], {}), '(X_trainFold)\n', (15445, 15458), True, 'import numpy as np\n'), ((15480, 15502), 'numpy.asarray', 'np.asarray', (['X_testFold'], {}), '(X_testFold)\n', (15490, 15502), True, 'import numpy as np\n'), ((15525, 15548), 'numpy.asarray', 'np.asarray', (['y_trainFold'], {}), '(y_trainFold)\n', (15535, 15548), True, 'import numpy as np\n'), ((15570, 15592), 'numpy.asarray', 'np.asarray', (['y_testFold'], {}), '(y_testFold)\n', (15580, 15592), True, 'import numpy as np\n'), ((26420, 26439), 'os.makedirs', 'os.makedirs', (['folder'], {}), '(folder)\n', (26431, 26439), False, 'import os\n'), ((26462, 26482), 'h5py.File', 'h5py.File', (['Path', '"""w"""'], {}), "(Path, 'w')\n", (26471, 26482), False, 'import h5py\n'), ((27671, 27701), 'numpy.where', 'np.where', (['(allPats != ind_split)'], {}), '(allPats != ind_split)\n', (27679, 27701), True, 'import numpy as np\n'), ((27730, 27760), 'numpy.where', 'np.where', (['(allPats == ind_split)'], {}), '(allPats == ind_split)\n', (27738, 27760), True, 'import numpy as np\n'), ((28680, 28701), 'os.path.isdir', 'os.path.isdir', (['folder'], {}), '(folder)\n', (28693, 28701), False, 'import os\n'), ((31307, 31325), 'numpy.unique', 'np.unique', (['allPats'], {}), '(allPats)\n', (31316, 31325), True, 'import numpy as np\n'), ((10501, 10520), 'os.makedirs', 'os.makedirs', (['folder'], {}), '(folder)\n', (10512, 10520), False, 'import os\n'), ((10543, 10563), 'h5py.File', 'h5py.File', (['Path', '"""w"""'], {}), "(Path, 'w')\n", (10552, 10563), False, 'import h5py\n'), ((12878, 12897), 'os.makedirs', 'os.makedirs', (['folder'], {}), '(folder)\n', (12889, 12897), False, 'import os\n'), ((12940, 12960), 'h5py.File', 'h5py.File', (['Path', '"""w"""'], {}), "(Path, 'w')\n", (12949, 12960), False, 'import h5py\n'), ((13591, 13613), 'sklearn.model_selection.KFold', 'KFold', ([], {'n_splits': 'nfolds'}), '(n_splits=nfolds)\n', (13596, 13613), False, 'from sklearn.model_selection import KFold\n'), ((15759, 15777), 'numpy.unique', 'np.unique', (['allPats'], {}), '(allPats)\n', (15768, 15777), True, 'import numpy as np\n'), ((17659, 17693), 'numpy.asarray', 'np.asarray', (['X_trainFold'], {'dtype': '"""f"""'}), "(X_trainFold, dtype='f')\n", (17669, 17693), True, 'import numpy as np\n'), ((17715, 17748), 'numpy.asarray', 'np.asarray', (['X_testFold'], {'dtype': '"""f"""'}), "(X_testFold, dtype='f')\n", (17725, 17748), True, 'import numpy as np\n'), ((17771, 17805), 'numpy.asarray', 'np.asarray', (['y_trainFold'], {'dtype': '"""f"""'}), "(y_trainFold, dtype='f')\n", (17781, 17805), True, 'import numpy as np\n'), ((17827, 17860), 'numpy.asarray', 'np.asarray', (['y_testFold'], {'dtype': '"""f"""'}), "(y_testFold, dtype='f')\n", (17837, 17860), True, 'import numpy as np\n'), ((28770, 28789), 'os.makedirs', 'os.makedirs', (['folder'], {}), '(folder)\n', (28781, 28789), False, 'import os\n'), ((28812, 28832), 'h5py.File', 'h5py.File', (['Path', '"""w"""'], {}), "(Path, 'w')\n", (28821, 28832), False, 'import h5py\n'), ((14646, 14667), 'os.path.isdir', 'os.path.isdir', (['folder'], {}), '(folder)\n', (14659, 14667), False, 'import os\n'), ((14736, 14755), 'os.makedirs', 'os.makedirs', (['folder'], {}), '(folder)\n', (14747, 14755), False, 'import os\n'), ((14778, 14798), 'h5py.File', 'h5py.File', (['Path', '"""w"""'], {}), "(Path, 'w')\n", (14787, 14798), False, 'import h5py\n'), ((15942, 15972), 'numpy.where', 'np.where', (['(allPats != ind_split)'], {}), '(allPats != ind_split)\n', (15950, 15972), True, 'import numpy as np\n'), ((16001, 16031), 'numpy.where', 'np.where', (['(allPats == ind_split)'], {}), '(allPats == ind_split)\n', (16009, 16031), True, 'import numpy as np\n'), ((16896, 16917), 'os.path.isdir', 'os.path.isdir', (['folder'], {}), '(folder)\n', (16909, 16917), False, 'import os\n'), ((13539, 13557), 'numpy.unique', 'np.unique', (['allPats'], {}), '(allPats)\n', (13548, 13557), True, 'import numpy as np\n'), ((16986, 17005), 'os.makedirs', 'os.makedirs', (['folder'], {}), '(folder)\n', (16997, 17005), False, 'import os\n'), ((17028, 17048), 'h5py.File', 'h5py.File', (['Path', '"""w"""'], {}), "(Path, 'w')\n", (17037, 17048), False, 'import h5py\n')] |
import json
import os
import re
import shutil
import numpy as np
import nibabel as nb
from itertools import chain
from pathlib import Path
from gzip import GzipFile
from nipype import logging
from nipype.utils.filemanip import copyfile
from nipype.interfaces.base import (
BaseInterfaceInputSpec,
TraitedSpec,
SimpleInterface,
InputMultiPath,
OutputMultiPath,
File,
Directory,
traits,
isdefined,
)
from nipype.interfaces.io import IOBase
from ..utils import snake_to_camel, to_alphanum
iflogger = logging.getLogger('nipype.interface')
ENTITY_WHITELIST = {
'task',
'run',
'session',
'subject',
'space',
'acquisition',
'reconstruction',
'echo',
}
def bids_split_filename(fname):
"""Split a filename into parts: path, base filename, and extension
Respects multi-part file types used in BIDS standard and draft extensions
Largely copied from nipype.utils.filemanip.split_filename
Parameters
----------
fname : str
file or path name
Returns
-------
pth : str
path of fname
fname : str
basename of filename, without extension
ext : str
file extension of fname
"""
special_extensions = [
".surf.gii",
".func.gii",
".dtseries.nii",
".dscalar.nii",
".nii.gz",
".tsv.gz",
]
pth = os.path.dirname(fname)
fname = os.path.basename(fname)
for special_ext in special_extensions:
if fname.lower().endswith(special_ext.lower()):
ext_len = len(special_ext)
ext = fname[-ext_len:]
fname = fname[:-ext_len]
break
else:
fname, ext = os.path.splitext(fname)
return pth, fname, ext
def _ensure_model(model):
model = getattr(model, 'filename', model)
if isinstance(model, str):
if os.path.exists(model):
with open(model) as fobj:
model = json.load(fobj)
else:
model = json.loads(model)
return model
class ModelSpecLoaderInputSpec(BaseInterfaceInputSpec):
database_path = Directory(exists=False, desc='Path to bids database')
model = traits.Either('default', InputMultiPath(File(exists=True)), desc='Model filename')
selectors = traits.Dict(desc='Limit models to those with matching inputs')
class ModelSpecLoaderOutputSpec(TraitedSpec):
model_spec = OutputMultiPath(
traits.Dict(), desc='Model specification(s) as Python dictionaries'
)
class ModelSpecLoader(SimpleInterface):
"""
Load BIDS Stats Models specifications from a BIDS directory
"""
input_spec = ModelSpecLoaderInputSpec
output_spec = ModelSpecLoaderOutputSpec
def _run_interface(self, runtime):
import bids
from bids.modeling import auto_model
models = self.inputs.model
if not isinstance(models, list):
database_path = self.inputs.database_path
layout = bids.BIDSLayout.load(database_path=database_path)
if not isdefined(models):
# model is not yet standardized, so validate=False
# Ignore all subject directories and .git/ and .datalad/ directories
indexer = bids.BIDSLayoutIndexer(
ignore=[re.compile(r'sub-'), re.compile(r'\.(git|datalad)')]
)
small_layout = bids.BIDSLayout(
layout.root,
derivatives=[d.root for d in layout.derivatives.values()],
validate=False,
indexer=indexer,
)
# PyBIDS can double up, so find unique models
models = list(set(small_layout.get(suffix='smdl', return_type='file')))
if not models:
raise ValueError("No models found")
elif models == 'default':
models = auto_model(layout)
models = [_ensure_model(m) for m in models]
if self.inputs.selectors:
# This is almost certainly incorrect
models = [
model
for model in models
if all(
val in model['Input'].get(key, [val])
for key, val in self.inputs.selectors.items()
)
]
self._results['model_spec'] = models
return runtime
IMPUTATION_SNIPPET = """\
<div class="warning">
The following confounds had NaN values for the first volume: {}.
The mean of non-zero values for the remaining entries was imputed.
If another strategy is desired, it must be explicitly specified in
the model.
</div>
"""
class LoadBIDSModelInputSpec(BaseInterfaceInputSpec):
database_path = Directory(exists=True, mandatory=True, desc='Path to bids database directory.')
model = traits.Dict(desc='Model specification', mandatory=True)
selectors = traits.Dict(desc='Limit collected sessions', usedefault=True)
class LoadBIDSModelOutputSpec(TraitedSpec):
design_info = traits.List(
traits.Dict,
desc='Descriptions of design matrices with sparse events, ' 'dense regressors and TR',
)
warnings = traits.List(File, desc='HTML warning snippet for reporting issues')
all_specs = traits.Dict(desc='A collection of all specs built from the statsmodel')
class LoadBIDSModel(SimpleInterface):
"""
Read a BIDS dataset and model and produce configurations that may be
adapted to various model-fitting packages.
Outputs
-------
design_info : list of list of dictionaries
At the first level, a dictionary per-run containing the following keys:
'sparse' : HDF5 file containing sparse representation of events
(onset, duration, amplitude)
'dense' : HDF5 file containing dense representation of events
regressors
'repetition_time' : float (in seconds)
all_specs : dictionary of list of dictionaries
The collection of specs from each level. Each dict at individual levels
contains the following keys:
'contrasts' : a list of ContrastInfo objects each unit of analysis.
A contrast specifiction is a list of contrast
dictionaries. Each dict has form:
{
'name': str,
'conditions': list,
'weights: list,
test: str,
'entities': dict,
}
'entities' : The entities list contains a list for each level of analysis.
At each level, the list contains a dictionary of entities that apply to
each unit of analysis. For example, if the level is "Run" and there are
20 runs in the dataset, the first entry will be a list of 20 dictionaries,
each uniquely identifying a run.
'level' : The current level of the analysis [run, subject, dataset...]
'X' : The design matrix
'model' : The model part from the BIDS-StatsModels specification.
'metadata' (only higher-levels): a parallel DataFrame with the same number of
rows as X that contains all known metadata variabes that vary on a row-by-row
basis but aren't actually predictiors
warnings : list of files
Files containing HTML snippets with any warnings produced while processing the first
level.
"""
input_spec = LoadBIDSModelInputSpec
output_spec = LoadBIDSModelOutputSpec
def _run_interface(self, runtime):
from bids.modeling import BIDSStatsModelsGraph
from bids.layout import BIDSLayout
layout = BIDSLayout.load(database_path=self.inputs.database_path)
selectors = self.inputs.selectors
graph = BIDSStatsModelsGraph(layout, self.inputs.model)
graph.load_collections(**selectors)
self._results['all_specs'] = self._load_graph(runtime, graph)
return runtime
def _load_graph(self, runtime, graph, node=None, inputs=None, **filters):
if node is None:
node = graph.root_node
specs = node.run(inputs, group_by=node.group_by, **filters)
outputs = list(chain(*[s.contrasts for s in specs]))
if node.level == 'run':
self._load_run_level(runtime, graph, specs)
all_specs = {
node.name: [
{
'contrasts': [c._asdict() for c in spec.contrasts],
'entities': spec.entities,
'level': spec.node.level,
'X': spec.X,
'name': spec.node.name,
'model': spec.node.model,
# Metadata is only used in higher level models; save space
'metadata': spec.metadata if spec.node.level != "run" else None,
}
for spec in specs
]
}
for child in node.children:
all_specs.update(
self._load_graph(runtime, graph, child.destination, outputs, **child.filter)
)
return all_specs
def _load_run_level(self, runtime, graph, specs):
design_info = []
warnings = []
step_subdir = Path(runtime.cwd) / "run"
step_subdir.mkdir(parents=True, exist_ok=True)
for spec in specs:
info = {}
if "RepetitionTime" not in spec.metadata:
# This shouldn't happen, so raise a (hopefully informative)
# exception if I'm wrong
fname = graph.layout.get(**spec.entities, suffix='bold')[0].path
raise ValueError(
f"Preprocessed file {fname} does not have an " "associated RepetitionTime"
)
info["repetition_time"] = spec.metadata['RepetitionTime'][0]
ent_string = '_'.join(f"{key}-{val}" for key, val in spec.entities.items())
# These confounds are defined pairwise with the current volume and its
# predecessor, and thus may be undefined (have value NaN) at the first volume.
# In these cases, we impute the mean non-zero value, for the expected NaN only.
# Any other NaNs must be handled by an explicit transform in the BIDS model.
imputed = []
for imputable in ('framewise_displacement', 'std_dvars', 'dvars'):
if imputable in spec.data.columns:
vals = spec.data[imputable].values
if not np.isnan(vals[0]):
continue
# Impute the mean non-zero, non-NaN value
spec.data[imputable][0] = np.nanmean(vals[vals != 0])
imputed.append(imputable)
info["dense"] = str(step_subdir / '{}_dense.h5'.format(ent_string))
spec.data.to_hdf(info["dense"], key='dense')
warning_file = step_subdir / '{}_warning.html'.format(ent_string)
with warning_file.open('w') as fobj:
if imputed:
fobj.write(IMPUTATION_SNIPPET.format(', '.join(imputed)))
design_info.append(info)
warnings.append(str(warning_file))
self._results['warnings'] = warnings
self._results['design_info'] = design_info
class BIDSSelectInputSpec(BaseInterfaceInputSpec):
database_path = Directory(exists=True, mandatory=True, desc='Path to bids database.')
entities = InputMultiPath(traits.Dict(), mandatory=True)
selectors = traits.Dict(desc='Additional selectors to be applied', usedefault=True)
class BIDSSelectOutputSpec(TraitedSpec):
bold_files = OutputMultiPath(File)
mask_files = OutputMultiPath(traits.Either(File, None))
entities = OutputMultiPath(traits.Dict)
class BIDSSelect(SimpleInterface):
input_spec = BIDSSelectInputSpec
output_spec = BIDSSelectOutputSpec
def _run_interface(self, runtime):
from bids.layout import BIDSLayout
layout = BIDSLayout.load(database_path=self.inputs.database_path)
bold_files = []
mask_files = []
entities = []
for ents in self.inputs.entities:
selectors = {'desc': 'preproc', **ents, **self.inputs.selectors}
bold_file = layout.get(**selectors)
if len(bold_file) == 0:
raise FileNotFoundError(
"Could not find BOLD file in {} with entities {}"
"".format(layout.root, selectors)
)
elif len(bold_file) > 1:
raise ValueError(
"Non-unique BOLD file in {} with entities {}.\n"
"Matches:\n\t{}"
"".format(
layout.root,
selectors,
"\n\t".join(
'{} ({})'.format(f.path, layout.files[f.path].entities)
for f in bold_file
),
)
)
# Select exactly matching mask file (may be over-cautious)
bold_ents = layout.parse_file_entities(bold_file[0].path)
bold_ents['suffix'] = 'mask'
bold_ents['desc'] = 'brain'
bold_ents['extension'] = ['.nii', '.nii.gz']
mask_file = layout.get(**bold_ents)
bold_ents.pop('suffix')
bold_ents.pop('desc')
bold_files.append(bold_file[0].path)
mask_files.append(mask_file[0].path if mask_file else None)
entities.append(bold_ents)
self._results['bold_files'] = bold_files
self._results['mask_files'] = mask_files
self._results['entities'] = entities
return runtime
def _copy_or_convert(in_file, out_file):
in_ext = bids_split_filename(in_file)[2]
out_ext = bids_split_filename(out_file)[2]
# Copy if filename matches
if in_ext == out_ext:
copyfile(in_file, out_file, copy=True, use_hardlink=True)
return
# gzip/gunzip if it's easy
if in_ext == out_ext + '.gz' or in_ext + '.gz' == out_ext:
read_open = GzipFile if in_ext.endswith('.gz') else open
write_open = GzipFile if out_ext.endswith('.gz') else open
with read_open(in_file, mode='rb') as in_fobj:
with write_open(out_file, mode='wb') as out_fobj:
shutil.copyfileobj(in_fobj, out_fobj)
return
# Let nibabel take a shot
try:
nb.save(nb.load(in_file), out_file)
except Exception:
pass
else:
return
raise RuntimeError("Cannot convert {} to {}".format(in_ext, out_ext))
class BIDSDataSinkInputSpec(BaseInterfaceInputSpec):
base_directory = Directory(mandatory=True, desc='Path to BIDS (or derivatives) root directory')
in_file = InputMultiPath(File(exists=True), mandatory=True)
entities = InputMultiPath(
traits.Dict, usedefault=True, desc='Per-file entities to include in filename'
)
fixed_entities = traits.Dict(usedefault=True, desc='Entities to include in all filenames')
path_patterns = InputMultiPath(
traits.Str, desc='BIDS path patterns describing format of file names'
)
class BIDSDataSinkOutputSpec(TraitedSpec):
out_file = OutputMultiPath(File, desc='output file')
class BIDSDataSink(IOBase):
input_spec = BIDSDataSinkInputSpec
output_spec = BIDSDataSinkOutputSpec
_always_run = True
_extension_map = {".nii": ".nii.gz"}
def _list_outputs(self):
from bids.layout import BIDSLayout
base_dir = self.inputs.base_directory
os.makedirs(base_dir, exist_ok=True)
layout = BIDSLayout(base_dir, validate=False)
path_patterns = self.inputs.path_patterns
if not isdefined(path_patterns):
path_patterns = None
out_files = []
for entities, in_file in zip(self.inputs.entities, self.inputs.in_file):
ents = {**self.inputs.fixed_entities}
ents.update(entities)
ext = bids_split_filename(in_file)[2]
ents['extension'] = self._extension_map.get(ext, ext)
# In some instances, name/contrast could have the following
# format (eg: gain.Range, gain.EqualIndifference).
# This prevents issues when creating/searching files for the report
for k, v in ents.items():
if k in ("name", "contrast", "stat"):
ents.update({k: to_alphanum(str(v))})
out_fname = os.path.join(
base_dir, layout.build_path(ents, path_patterns, validate=False)
)
os.makedirs(os.path.dirname(out_fname), exist_ok=True)
_copy_or_convert(in_file, out_fname)
out_files.append(out_fname)
return {'out_file': out_files}
| [
"bids.layout.BIDSLayout.load",
"numpy.isnan",
"pathlib.Path",
"nipype.interfaces.base.isdefined",
"numpy.nanmean",
"json.loads",
"os.path.dirname",
"os.path.exists",
"nipype.interfaces.base.InputMultiPath",
"nipype.interfaces.base.Directory",
"nipype.interfaces.base.traits.List",
"nipype.inter... | [((538, 575), 'nipype.logging.getLogger', 'logging.getLogger', (['"""nipype.interface"""'], {}), "('nipype.interface')\n", (555, 575), False, 'from nipype import logging\n'), ((1391, 1413), 'os.path.dirname', 'os.path.dirname', (['fname'], {}), '(fname)\n', (1406, 1413), False, 'import os\n'), ((1426, 1449), 'os.path.basename', 'os.path.basename', (['fname'], {}), '(fname)\n', (1442, 1449), False, 'import os\n'), ((2127, 2180), 'nipype.interfaces.base.Directory', 'Directory', ([], {'exists': '(False)', 'desc': '"""Path to bids database"""'}), "(exists=False, desc='Path to bids database')\n", (2136, 2180), False, 'from nipype.interfaces.base import BaseInterfaceInputSpec, TraitedSpec, SimpleInterface, InputMultiPath, OutputMultiPath, File, Directory, traits, isdefined\n'), ((2292, 2354), 'nipype.interfaces.base.traits.Dict', 'traits.Dict', ([], {'desc': '"""Limit models to those with matching inputs"""'}), "(desc='Limit models to those with matching inputs')\n", (2303, 2354), False, 'from nipype.interfaces.base import BaseInterfaceInputSpec, TraitedSpec, SimpleInterface, InputMultiPath, OutputMultiPath, File, Directory, traits, isdefined\n'), ((4776, 4855), 'nipype.interfaces.base.Directory', 'Directory', ([], {'exists': '(True)', 'mandatory': '(True)', 'desc': '"""Path to bids database directory."""'}), "(exists=True, mandatory=True, desc='Path to bids database directory.')\n", (4785, 4855), False, 'from nipype.interfaces.base import BaseInterfaceInputSpec, TraitedSpec, SimpleInterface, InputMultiPath, OutputMultiPath, File, Directory, traits, isdefined\n'), ((4868, 4923), 'nipype.interfaces.base.traits.Dict', 'traits.Dict', ([], {'desc': '"""Model specification"""', 'mandatory': '(True)'}), "(desc='Model specification', mandatory=True)\n", (4879, 4923), False, 'from nipype.interfaces.base import BaseInterfaceInputSpec, TraitedSpec, SimpleInterface, InputMultiPath, OutputMultiPath, File, Directory, traits, isdefined\n'), ((4940, 5001), 'nipype.interfaces.base.traits.Dict', 'traits.Dict', ([], {'desc': '"""Limit collected sessions"""', 'usedefault': '(True)'}), "(desc='Limit collected sessions', usedefault=True)\n", (4951, 5001), False, 'from nipype.interfaces.base import BaseInterfaceInputSpec, TraitedSpec, SimpleInterface, InputMultiPath, OutputMultiPath, File, Directory, traits, isdefined\n'), ((5066, 5184), 'nipype.interfaces.base.traits.List', 'traits.List', (['traits.Dict'], {'desc': '"""Descriptions of design matrices with sparse events, dense regressors and TR"""'}), "(traits.Dict, desc=\n 'Descriptions of design matrices with sparse events, dense regressors and TR'\n )\n", (5077, 5184), False, 'from nipype.interfaces.base import BaseInterfaceInputSpec, TraitedSpec, SimpleInterface, InputMultiPath, OutputMultiPath, File, Directory, traits, isdefined\n'), ((5216, 5283), 'nipype.interfaces.base.traits.List', 'traits.List', (['File'], {'desc': '"""HTML warning snippet for reporting issues"""'}), "(File, desc='HTML warning snippet for reporting issues')\n", (5227, 5283), False, 'from nipype.interfaces.base import BaseInterfaceInputSpec, TraitedSpec, SimpleInterface, InputMultiPath, OutputMultiPath, File, Directory, traits, isdefined\n'), ((5300, 5371), 'nipype.interfaces.base.traits.Dict', 'traits.Dict', ([], {'desc': '"""A collection of all specs built from the statsmodel"""'}), "(desc='A collection of all specs built from the statsmodel')\n", (5311, 5371), False, 'from nipype.interfaces.base import BaseInterfaceInputSpec, TraitedSpec, SimpleInterface, InputMultiPath, OutputMultiPath, File, Directory, traits, isdefined\n'), ((11517, 11586), 'nipype.interfaces.base.Directory', 'Directory', ([], {'exists': '(True)', 'mandatory': '(True)', 'desc': '"""Path to bids database."""'}), "(exists=True, mandatory=True, desc='Path to bids database.')\n", (11526, 11586), False, 'from nipype.interfaces.base import BaseInterfaceInputSpec, TraitedSpec, SimpleInterface, InputMultiPath, OutputMultiPath, File, Directory, traits, isdefined\n'), ((11664, 11735), 'nipype.interfaces.base.traits.Dict', 'traits.Dict', ([], {'desc': '"""Additional selectors to be applied"""', 'usedefault': '(True)'}), "(desc='Additional selectors to be applied', usedefault=True)\n", (11675, 11735), False, 'from nipype.interfaces.base import BaseInterfaceInputSpec, TraitedSpec, SimpleInterface, InputMultiPath, OutputMultiPath, File, Directory, traits, isdefined\n'), ((11796, 11817), 'nipype.interfaces.base.OutputMultiPath', 'OutputMultiPath', (['File'], {}), '(File)\n', (11811, 11817), False, 'from nipype.interfaces.base import BaseInterfaceInputSpec, TraitedSpec, SimpleInterface, InputMultiPath, OutputMultiPath, File, Directory, traits, isdefined\n'), ((11893, 11921), 'nipype.interfaces.base.OutputMultiPath', 'OutputMultiPath', (['traits.Dict'], {}), '(traits.Dict)\n', (11908, 11921), False, 'from nipype.interfaces.base import BaseInterfaceInputSpec, TraitedSpec, SimpleInterface, InputMultiPath, OutputMultiPath, File, Directory, traits, isdefined\n'), ((14875, 14953), 'nipype.interfaces.base.Directory', 'Directory', ([], {'mandatory': '(True)', 'desc': '"""Path to BIDS (or derivatives) root directory"""'}), "(mandatory=True, desc='Path to BIDS (or derivatives) root directory')\n", (14884, 14953), False, 'from nipype.interfaces.base import BaseInterfaceInputSpec, TraitedSpec, SimpleInterface, InputMultiPath, OutputMultiPath, File, Directory, traits, isdefined\n'), ((15033, 15131), 'nipype.interfaces.base.InputMultiPath', 'InputMultiPath', (['traits.Dict'], {'usedefault': '(True)', 'desc': '"""Per-file entities to include in filename"""'}), "(traits.Dict, usedefault=True, desc=\n 'Per-file entities to include in filename')\n", (15047, 15131), False, 'from nipype.interfaces.base import BaseInterfaceInputSpec, TraitedSpec, SimpleInterface, InputMultiPath, OutputMultiPath, File, Directory, traits, isdefined\n'), ((15162, 15235), 'nipype.interfaces.base.traits.Dict', 'traits.Dict', ([], {'usedefault': '(True)', 'desc': '"""Entities to include in all filenames"""'}), "(usedefault=True, desc='Entities to include in all filenames')\n", (15173, 15235), False, 'from nipype.interfaces.base import BaseInterfaceInputSpec, TraitedSpec, SimpleInterface, InputMultiPath, OutputMultiPath, File, Directory, traits, isdefined\n'), ((15256, 15346), 'nipype.interfaces.base.InputMultiPath', 'InputMultiPath', (['traits.Str'], {'desc': '"""BIDS path patterns describing format of file names"""'}), "(traits.Str, desc=\n 'BIDS path patterns describing format of file names')\n", (15270, 15346), False, 'from nipype.interfaces.base import BaseInterfaceInputSpec, TraitedSpec, SimpleInterface, InputMultiPath, OutputMultiPath, File, Directory, traits, isdefined\n'), ((15416, 15457), 'nipype.interfaces.base.OutputMultiPath', 'OutputMultiPath', (['File'], {'desc': '"""output file"""'}), "(File, desc='output file')\n", (15431, 15457), False, 'from nipype.interfaces.base import BaseInterfaceInputSpec, TraitedSpec, SimpleInterface, InputMultiPath, OutputMultiPath, File, Directory, traits, isdefined\n'), ((1710, 1733), 'os.path.splitext', 'os.path.splitext', (['fname'], {}), '(fname)\n', (1726, 1733), False, 'import os\n'), ((1879, 1900), 'os.path.exists', 'os.path.exists', (['model'], {}), '(model)\n', (1893, 1900), False, 'import os\n'), ((2445, 2458), 'nipype.interfaces.base.traits.Dict', 'traits.Dict', ([], {}), '()\n', (2456, 2458), False, 'from nipype.interfaces.base import BaseInterfaceInputSpec, TraitedSpec, SimpleInterface, InputMultiPath, OutputMultiPath, File, Directory, traits, isdefined\n'), ((7789, 7845), 'bids.layout.BIDSLayout.load', 'BIDSLayout.load', ([], {'database_path': 'self.inputs.database_path'}), '(database_path=self.inputs.database_path)\n', (7804, 7845), False, 'from bids.layout import BIDSLayout\n'), ((7905, 7952), 'bids.modeling.BIDSStatsModelsGraph', 'BIDSStatsModelsGraph', (['layout', 'self.inputs.model'], {}), '(layout, self.inputs.model)\n', (7925, 7952), False, 'from bids.modeling import BIDSStatsModelsGraph\n'), ((11617, 11630), 'nipype.interfaces.base.traits.Dict', 'traits.Dict', ([], {}), '()\n', (11628, 11630), False, 'from nipype.interfaces.base import BaseInterfaceInputSpec, TraitedSpec, SimpleInterface, InputMultiPath, OutputMultiPath, File, Directory, traits, isdefined\n'), ((11851, 11876), 'nipype.interfaces.base.traits.Either', 'traits.Either', (['File', 'None'], {}), '(File, None)\n', (11864, 11876), False, 'from nipype.interfaces.base import BaseInterfaceInputSpec, TraitedSpec, SimpleInterface, InputMultiPath, OutputMultiPath, File, Directory, traits, isdefined\n'), ((12136, 12192), 'bids.layout.BIDSLayout.load', 'BIDSLayout.load', ([], {'database_path': 'self.inputs.database_path'}), '(database_path=self.inputs.database_path)\n', (12151, 12192), False, 'from bids.layout import BIDSLayout\n'), ((14094, 14151), 'nipype.utils.filemanip.copyfile', 'copyfile', (['in_file', 'out_file'], {'copy': '(True)', 'use_hardlink': '(True)'}), '(in_file, out_file, copy=True, use_hardlink=True)\n', (14102, 14151), False, 'from nipype.utils.filemanip import copyfile\n'), ((14983, 15000), 'nipype.interfaces.base.File', 'File', ([], {'exists': '(True)'}), '(exists=True)\n', (14987, 15000), False, 'from nipype.interfaces.base import BaseInterfaceInputSpec, TraitedSpec, SimpleInterface, InputMultiPath, OutputMultiPath, File, Directory, traits, isdefined\n'), ((15762, 15798), 'os.makedirs', 'os.makedirs', (['base_dir'], {'exist_ok': '(True)'}), '(base_dir, exist_ok=True)\n', (15773, 15798), False, 'import os\n'), ((15817, 15853), 'bids.layout.BIDSLayout', 'BIDSLayout', (['base_dir'], {'validate': '(False)'}), '(base_dir, validate=False)\n', (15827, 15853), False, 'from bids.layout import BIDSLayout\n'), ((2014, 2031), 'json.loads', 'json.loads', (['model'], {}), '(model)\n', (2024, 2031), False, 'import json\n'), ((2233, 2250), 'nipype.interfaces.base.File', 'File', ([], {'exists': '(True)'}), '(exists=True)\n', (2237, 2250), False, 'from nipype.interfaces.base import BaseInterfaceInputSpec, TraitedSpec, SimpleInterface, InputMultiPath, OutputMultiPath, File, Directory, traits, isdefined\n'), ((2985, 3034), 'bids.BIDSLayout.load', 'bids.BIDSLayout.load', ([], {'database_path': 'database_path'}), '(database_path=database_path)\n', (3005, 3034), False, 'import bids\n'), ((8323, 8359), 'itertools.chain', 'chain', (['*[s.contrasts for s in specs]'], {}), '(*[s.contrasts for s in specs])\n', (8328, 8359), False, 'from itertools import chain\n'), ((9369, 9386), 'pathlib.Path', 'Path', (['runtime.cwd'], {}), '(runtime.cwd)\n', (9373, 9386), False, 'from pathlib import Path\n'), ((14636, 14652), 'nibabel.load', 'nb.load', (['in_file'], {}), '(in_file)\n', (14643, 14652), True, 'import nibabel as nb\n'), ((15919, 15943), 'nipype.interfaces.base.isdefined', 'isdefined', (['path_patterns'], {}), '(path_patterns)\n', (15928, 15943), False, 'from nipype.interfaces.base import BaseInterfaceInputSpec, TraitedSpec, SimpleInterface, InputMultiPath, OutputMultiPath, File, Directory, traits, isdefined\n'), ((1964, 1979), 'json.load', 'json.load', (['fobj'], {}), '(fobj)\n', (1973, 1979), False, 'import json\n'), ((3055, 3072), 'nipype.interfaces.base.isdefined', 'isdefined', (['models'], {}), '(models)\n', (3064, 3072), False, 'from nipype.interfaces.base import BaseInterfaceInputSpec, TraitedSpec, SimpleInterface, InputMultiPath, OutputMultiPath, File, Directory, traits, isdefined\n'), ((14527, 14564), 'shutil.copyfileobj', 'shutil.copyfileobj', (['in_fobj', 'out_fobj'], {}), '(in_fobj, out_fobj)\n', (14545, 14564), False, 'import shutil\n'), ((16807, 16833), 'os.path.dirname', 'os.path.dirname', (['out_fname'], {}), '(out_fname)\n', (16822, 16833), False, 'import os\n'), ((3926, 3944), 'bids.modeling.auto_model', 'auto_model', (['layout'], {}), '(layout)\n', (3936, 3944), False, 'from bids.modeling import auto_model\n'), ((10816, 10843), 'numpy.nanmean', 'np.nanmean', (['vals[vals != 0]'], {}), '(vals[vals != 0])\n', (10826, 10843), True, 'import numpy as np\n'), ((10655, 10672), 'numpy.isnan', 'np.isnan', (['vals[0]'], {}), '(vals[0])\n', (10663, 10672), True, 'import numpy as np\n'), ((3304, 3322), 're.compile', 're.compile', (['"""sub-"""'], {}), "('sub-')\n", (3314, 3322), False, 'import re\n'), ((3325, 3355), 're.compile', 're.compile', (['"""\\\\.(git|datalad)"""'], {}), "('\\\\.(git|datalad)')\n", (3335, 3355), False, 'import re\n')] |
# encoding: utf-8
# Created: 2021/10/13
import logging
import math
import os
from collections import defaultdict
from typing import Dict, List
import numpy as np
import torch
import transformations
import yaml
try:
from yaml import CLoader as Loader, CDumper as Dumper
except ImportError:
from yaml import Loader, Dumper
from torch.utils import data
from tqdm import tqdm
from src.utils.libpc import crop_pc_2d, crop_pc_2d_index
from src.utils.libcoord.coord_transform import invert_transform, apply_transform
from src.io.RasterIO import RasterReader, RasterData
LAND_TYPES = ['building', 'forest', 'water']
LAND_TYPE_IDX = {LAND_TYPES[i]: i for i in range(len(LAND_TYPES))}
# constant for data augmentation
_origin = np.array([0., 0., 0.])
_x_axis = np.array([1., 0., 0.])
_y_axis = np.array([0., 1., 0.])
z_axis = np.array([0., 0., 1.])
# Rotation matrix: rotate nx90 deg clockwise
rot_mat_dic: Dict[int, torch.Tensor] = {
0: torch.eye(4).double(),
1: torch.as_tensor(transformations.rotation_matrix(-90. * math.pi / 180., z_axis)).double(),
2: torch.as_tensor(transformations.rotation_matrix(-180. * math.pi / 180., z_axis)).double(),
3: torch.as_tensor(transformations.rotation_matrix(-270. * math.pi / 180., z_axis)).double(),
}
# Flip matrix
flip_mat_dic: Dict[int, torch.Tensor] = {
-1: torch.eye(4).double(),
0: torch.as_tensor(transformations.reflection_matrix(_origin, _x_axis)).double(), # flip on x direction (x := -x)
1: torch.as_tensor(transformations.reflection_matrix(_origin, _y_axis)).double() # flip on y direction (y := -y)
}
class ImpliCityDataset(data.Dataset):
""" Load ResDepth Dataset
for train/val: {'name', 'inputs', 'transform', 'query_pts', 'query_occ', 'mask_gt', 'mask_building', 'mask_forest', 'mask_water'}
for test/vis: {'name', 'inputs', 'transform'}
"""
# pre-defined filenames
INPUT_POINT_CLOUD = "input_point_cloud.npz"
QUERY_POINTS = "query--%s.npz"
CHUNK_INFO = "chunk_info.yaml"
def __init__(self, split: str, cfg_dataset: Dict, random_sample=False, merge_query_occ: bool = True,
random_length=None, flip_augm=False, rotate_augm=False):
"""
Args:
split: 'train', 'val', 'test', 'vis'
cfg_dataset: dataset configurations
random_sample: randomly sample patches. if False, use sliding window (parameters are given in cfg_dataset)
random_length: length of dataset, valid only if random_sample is True,
merge_query_occ: merge occupancy labels to binary case
flip_augm: data augmentation by flipping
rotate_augm: data augmentation by rotation
"""
# shortcuts
self.split = split
self._dataset_folder = cfg_dataset['path']
self._cfg_data = cfg_dataset
self._n_input_pts = cfg_dataset['n_input_points']
self._n_query_pts = cfg_dataset['n_query_points']
if self.split in ['val'] and not cfg_dataset.get('subsample_val', False):
self._n_query_pts = None
self.patch_size = torch.tensor(cfg_dataset['patch_size'], dtype=torch.float64)
# initialize
self.images: List[RasterData] = []
self.data_dic = defaultdict()
self.dataset_chunk_idx_ls: List = cfg_dataset[f"{split}_chunks"]
dataset_dir = self._cfg_data['path']
with open(os.path.join(dataset_dir, self.CHUNK_INFO), 'r') as f:
self.chunk_info: Dict = yaml.load(f, Loader=Loader)
self.chunk_info_ls: List = [self.chunk_info[i] for i in self.dataset_chunk_idx_ls]
# -------------------- Load satellite image --------------------
images_dic = self._cfg_data.get('satellite_image', None)
if images_dic is not None:
image_folder = images_dic['folder']
for image_name in images_dic['pairs']:
_path = os.path.join(image_folder, image_name)
reader = RasterReader(_path)
self.images.append(reader)
logging.debug(f"Satellite image loaded: {image_name}")
assert len(self.images) <= 2, "Only support single image or stereo image"
assert self.images[-1].T == self.images[0].T
temp_ls = []
for _img in self.images:
_img_arr = _img.get_data().astype(np.int32)
temp_ls.append(torch.from_numpy(_img_arr[None, :, :]))
self.norm_image_data: torch.Tensor = torch.cat(temp_ls, 0).long()
self.norm_image_data = self.norm_image_data.reshape(
(-1, self.norm_image_data.shape[-2], self.norm_image_data.shape[-1])) # n_img x h_image x w_image
# Normalize values
self._image_mean = images_dic['normalize']['mean']
self._image_std = images_dic['normalize']['std']
self.norm_image_data: torch.Tensor = (self.norm_image_data.double() - self._image_mean) / self._image_std
self.n_images = len(self.images)
if self.n_images > 0:
self._image_pixel_size = torch.as_tensor(self.images[0].pixel_size, dtype=torch.float64)
self._image_patch_shape = self.patch_size / self._image_pixel_size
assert torch.all(torch.floor(self._image_patch_shape) == self._image_patch_shape),\
"Patch size should be integer multiple of image pixel size"
self._image_patch_shape = torch.floor(self._image_patch_shape).long()
# -------------------- Load point data by chunks --------------------
for chunk_idx in tqdm(self.dataset_chunk_idx_ls, desc=f"Loading {self.split} data to RAM"):
info = self.chunk_info[chunk_idx]
chunk_name = info['name']
chunk_full_path = os.path.join(dataset_dir, chunk_name)
# input points
inputs = np.load(os.path.join(chunk_full_path, self.INPUT_POINT_CLOUD))
chunk_data = {
'name': chunk_name,
'inputs': torch.from_numpy(inputs['pts']).double(),
}
# query points
if self.split in ['train', 'val']:
query_types = ['uniform']
use_surface = self._cfg_data['use_surface']
if use_surface is not None:
query_types.extend(use_surface)
query_pts_ls: List = []
query_occ_ls: List = []
masks_ls: Dict[str, List] = {f'mask_{_m}': [] for _m in ['gt', 'building', 'forest', 'water']}
for surface_type in query_types:
file_path = os.path.join(chunk_full_path, self.QUERY_POINTS % surface_type)
_loaded = np.load(file_path)
query_pts_ls.append(_loaded['pts'])
query_occ_ls.append(_loaded['occ'])
for _m in masks_ls.keys(): # e.g. mask_gt
masks_ls[_m].append(_loaded[_m])
query_pts: np.ndarray = np.concatenate(query_pts_ls, 0)
query_occ: np.ndarray = np.concatenate(query_occ_ls, 0)
masks: Dict[str, np.ndarray] = {_m: np.concatenate(masks_ls[_m], 0) for _m in masks_ls.keys()}
if merge_query_occ:
query_occ = (query_occ > 0).astype(bool)
del query_pts_ls, query_occ_ls, masks_ls
chunk_data.update({
'query_pts': torch.from_numpy(query_pts).double(),
'query_occ': torch.from_numpy(query_occ).float(),
'mask_gt': torch.from_numpy(masks['mask_gt']).bool(),
'mask_building': torch.from_numpy(masks['mask_building']).bool(),
'mask_forest': torch.from_numpy(masks['mask_forest']).bool(),
'mask_water': torch.from_numpy(masks['mask_water']).bool(),
})
self.data_dic[chunk_idx] = chunk_data
self.random_sample = random_sample
self.random_length = random_length
if self.random_sample and random_length is None:
logging.warning("random_length not provided when random_sample = True")
self.random_length = 10
self.flip_augm = flip_augm
self.rotate_augm = rotate_augm
# -------------------- Generate Anchors --------------------
# bottom-left point of a patch, for regular patch
self.anchor_points: List[Dict] = [] # [{chunk_idx: int, anchors: [np.array(2), ...]}, ... ]
if not self.random_sample:
self.slide_window_strip = cfg_dataset['sliding_window'][f'{self.split}_strip']
for chunk_idx in self.dataset_chunk_idx_ls:
chunk_info = self.chunk_info[chunk_idx]
_min_bound_np = np.array(chunk_info['min_bound'])
_max_bound_np = np.array(chunk_info['max_bound'])
_chunk_size_np = _max_bound_np - _min_bound_np
patch_x_np = np.arange(_min_bound_np[0], _max_bound_np[0] - self.patch_size[0], self.slide_window_strip[0])
patch_x_np = np.concatenate([patch_x_np, np.array([_max_bound_np[0] - self.patch_size[0]])])
patch_y_np = np.arange(_min_bound_np[1], _max_bound_np[1] - self.patch_size[1], self.slide_window_strip[1])
patch_y_np = np.concatenate([patch_y_np, np.array([_max_bound_np[1] - self.patch_size[1]])])
# print('patch_y', patch_y.shape, patch_y)
xv, yv = np.meshgrid(patch_x_np, patch_y_np)
anchors = np.concatenate([xv.reshape((-1, 1)), yv.reshape((-1, 1))], 1)
anchors = torch.from_numpy(anchors).double()
# print('anchors', anchors.shape)
for anchor in anchors:
self.anchor_points.append({
'chunk_idx': chunk_idx,
'anchor': anchor
})
# -------------------- normalization factors --------------------
_x_range = cfg_dataset['normalize']['x_range']
_y_range = cfg_dataset['normalize']['y_range']
self._min_norm_bound = [_x_range[0], _y_range[0]]
self._max_norm_bound = [_x_range[1], _y_range[1]]
self.z_std = cfg_dataset['normalize']['z_std']
self.scale_mat = torch.diag(torch.tensor([self.patch_size[0] / (_x_range[1] - _x_range[0]),
self.patch_size[1] / (_y_range[1] - _y_range[0]),
self.z_std,
1], dtype=torch.float64))
self.shift_norm = torch.cat([torch.eye(4, 3, dtype=torch.float64),
torch.tensor([(_x_range[1] - _x_range[0]) / 2.,
(_y_range[1] - _y_range[0]) / 2., 0, 1]).reshape(-1, 1)], 1) # shift from [-0.5, 0.5] to [0, 1]
def __len__(self):
if self.random_sample:
return self.random_length
else:
return len(self.anchor_points)
def __getitem__(self, idx):
"""
Get patch data and assemble point clouds for training.
Args:
idx: index of data
Returns: a dict of data
"""
# -------------------- Get patch anchor point --------------------
if self.random_sample:
# randomly choose anchors
# chunk_idx = idx % len(self.dataset_chunk_idx_ls)
chunk_idx = self.dataset_chunk_idx_ls[idx % len(self.dataset_chunk_idx_ls)]
chunk_info = self.chunk_info[chunk_idx]
_min_bound = torch.tensor(chunk_info['min_bound'], dtype=torch.float64)
_max_bound = torch.tensor(chunk_info['max_bound'], dtype=torch.float64)
_chunk_size = _max_bound - _min_bound
_rand = torch.rand(2, dtype=torch.float64)
anchor = _rand * (_chunk_size[:2] - self.patch_size[:2])
if self.n_images > 0:
anchor = torch.floor(anchor / self._image_pixel_size) * self._image_pixel_size
# print('anchor: ', anchor)
anchor += _min_bound[:2]
else:
# regular patches
_anchor_info = self.anchor_points[idx]
chunk_idx = _anchor_info['chunk_idx']
anchor = _anchor_info['anchor']
min_bound = anchor
max_bound = anchor + self.patch_size.double()
assert chunk_idx in self.dataset_chunk_idx_ls
assert torch.float64 == min_bound.dtype # for geo-coordinate, must use float64
# -------------------- Input point cloud --------------------
# Crop inputs
chunk_data = self.data_dic[chunk_idx]
inputs, _ = crop_pc_2d(chunk_data['inputs'], min_bound, max_bound)
shift_strategy = self._cfg_data['normalize']['z_shift']
if 'median' == shift_strategy:
z_shift = torch.median(inputs[:, 2]).double().reshape(1)
elif '20quantile' == shift_strategy:
z_shift = torch.tensor([np.quantile(inputs[:, 2].numpy(), 0.2)])
elif 'mean' == shift_strategy:
z_shift = torch.mean(inputs[:, 2]).double().reshape(1)
else:
raise ValueError(f"Unknown shift strategy: {shift_strategy}")
# subsample inputs
if self._n_input_pts is not None and inputs.shape[0] > self._n_input_pts:
_idx = np.random.choice(inputs.shape[0], self._n_input_pts)
inputs = inputs[_idx]
# print('inputs: ', inputs.min(0)[0], inputs.max(0)[0])
# print('min_bound: ', min_bound)
# print('z_shift: ', z_shift)
# print('inputs first point: ', inputs[0])
# print('diff: ', inputs[0] - torch.cat([min_bound, z_shift]))
# -------------------- Augmentation --------------------
if self.rotate_augm:
rot_times = list(rot_mat_dic.keys())[np.random.choice(len(rot_mat_dic))]
# rot_mat = rot_mat_ls[np.random.choice(len(rot_mat_ls))]
else:
# rot_mat = rot_mat_ls[0]
rot_times = 0
rot_mat = rot_mat_dic[rot_times]
if self.flip_augm:
flip_dim_pc = list(flip_mat_dic.keys())[np.random.choice(len(flip_mat_dic))]
# flip_mat = flip_mat_ls[np.random.choice(len(flip_mat_ls))]
else:
# flip_mat = flip_mat_ls[0]
flip_dim_pc = -1
flip_mat = flip_mat_dic[flip_dim_pc]
# -------------------- Normalization --------------------
# Normalization matrix
# Transformation matrix: normalize to [-0.5, 0.5]
transform_mat = self.scale_mat.clone()
transform_mat[0:3, 3] = torch.cat([(min_bound + max_bound)/2., z_shift], 0)
normalize_mat = self.shift_norm.double() @ flip_mat.double() @ rot_mat.double() \
@ invert_transform(transform_mat).double()
transform_mat = invert_transform(normalize_mat)
assert torch.float64 == transform_mat.dtype
# Normalize inputs
inputs_norm = apply_transform(inputs, normalize_mat)
inputs_norm = inputs_norm.float()
# print('normalized inputs, first point: ', inputs_norm[0])
# crop again (in case of calculation error)
inputs_norm, _ = crop_pc_2d(inputs_norm, self._min_norm_bound, self._max_norm_bound)
# # debug only
# assert torch.min(inputs_norm[:, :2]) > 0
# assert torch.max(inputs_norm[:, :2]) < 1
out_data = {
'name': f"{chunk_data['name']}-patch{idx}",
'inputs': inputs_norm,
'transform': transform_mat.double().clone(),
'min_bound': min_bound.double().clone(),
'max_bound': max_bound.double().clone(),
'flip': flip_dim_pc,
'rotate': rot_times
}
# -------------------- Query points --------------------
if self.split in ['train', 'val']:
# Crop query points
points, points_idx = crop_pc_2d(chunk_data['query_pts'], min_bound, max_bound)
# print('points, first point: ', points[0])
# print('diff: ', points[0] - torch.cat([min_bound, z_shift]))
# Normalize query points
points_norm = apply_transform(points, normalize_mat)
# print('normalized points, first point: ', points_norm[0])
points_norm = points_norm.float()
# crop again in case of calculation error
points_idx2 = crop_pc_2d_index(points_norm, self._min_norm_bound, self._max_norm_bound)
points_norm = points_norm[points_idx2]
points_idx = points_idx[points_idx2]
# # debug only
# assert torch.min(points_norm[:, :2]) > 0
# assert torch.max(points_norm[:, :2]) < 1
# points_idx = crop_pc_2d_index(chunk_data['query_pts'], min_bound, max_bound)
# print(points_idx.shape)
if self._n_query_pts is not None and points_idx.shape[0] > self._n_query_pts:
_idx = np.random.choice(points_idx.shape[0], self._n_query_pts)
points_norm = points_norm[_idx]
points_idx = points_idx[_idx]
# points = chunk_data['query_pts'][points_idx]
# print(points.shape)
out_data['query_pts'] = points_norm
out_data['query_occ'] = chunk_data['query_occ'][points_idx].float()
# assign occ and mask_land
for _m in ['mask_gt', 'mask_building', 'mask_forest', 'mask_water']:
out_data[_m] = chunk_data[_m][points_idx]
# -------------------- Image --------------------
if self.n_images > 0:
# index of bottom-left pixel center
_anchor_pixel_center = anchor + self._image_pixel_size / 2.
_col, _row = self.images[0].query_col_row(_anchor_pixel_center[0], _anchor_pixel_center[1])
_image_patches = []
shape = self._image_patch_shape
image_tensor = self.norm_image_data[:, _row-shape[0]+1:_row+1, _col:_col+shape[1]] # n_img x h_patch x w_patch
# Augmentation
if rot_times > 0:
image_tensor = image_tensor.rot90(rot_times, [-1, -2]) # rotate clockwise
if flip_dim_pc >= 0:
if 0 == flip_dim_pc: # points flip on x direction (along y), image flip columns
image_tensor = image_tensor.flip(-1)
if 1 == flip_dim_pc: # points flip on y direction (along x), image flip rows
image_tensor = image_tensor.flip(-2)
# image_tensor = image_tensor.flip(flip_axis+1) # dim 0 is image dimension
assert torch.Size([self.n_images, shape[0], shape[1]]) == image_tensor.shape, f"shape: {torch.Size([self.n_images, shape[0], shape[1]])}image_tensor.shape: {image_tensor.shape}, _row: {_row}, _col: {_col}"
out_data['image'] = image_tensor.float()
return out_data
| [
"yaml.load",
"numpy.load",
"torch.eye",
"src.utils.libcoord.coord_transform.apply_transform",
"src.io.RasterIO.RasterReader",
"src.utils.libpc.crop_pc_2d",
"torch.cat",
"collections.defaultdict",
"numpy.arange",
"os.path.join",
"torch.median",
"numpy.meshgrid",
"transformations.reflection_ma... | [((731, 756), 'numpy.array', 'np.array', (['[0.0, 0.0, 0.0]'], {}), '([0.0, 0.0, 0.0])\n', (739, 756), True, 'import numpy as np\n'), ((764, 789), 'numpy.array', 'np.array', (['[1.0, 0.0, 0.0]'], {}), '([1.0, 0.0, 0.0])\n', (772, 789), True, 'import numpy as np\n'), ((797, 822), 'numpy.array', 'np.array', (['[0.0, 1.0, 0.0]'], {}), '([0.0, 1.0, 0.0])\n', (805, 822), True, 'import numpy as np\n'), ((829, 854), 'numpy.array', 'np.array', (['[0.0, 0.0, 1.0]'], {}), '([0.0, 0.0, 1.0])\n', (837, 854), True, 'import numpy as np\n'), ((3103, 3163), 'torch.tensor', 'torch.tensor', (["cfg_dataset['patch_size']"], {'dtype': 'torch.float64'}), "(cfg_dataset['patch_size'], dtype=torch.float64)\n", (3115, 3163), False, 'import torch\n'), ((3253, 3266), 'collections.defaultdict', 'defaultdict', ([], {}), '()\n', (3264, 3266), False, 'from collections import defaultdict\n'), ((5584, 5657), 'tqdm.tqdm', 'tqdm', (['self.dataset_chunk_idx_ls'], {'desc': 'f"""Loading {self.split} data to RAM"""'}), "(self.dataset_chunk_idx_ls, desc=f'Loading {self.split} data to RAM')\n", (5588, 5657), False, 'from tqdm import tqdm\n'), ((12742, 12796), 'src.utils.libpc.crop_pc_2d', 'crop_pc_2d', (["chunk_data['inputs']", 'min_bound', 'max_bound'], {}), "(chunk_data['inputs'], min_bound, max_bound)\n", (12752, 12796), False, 'from src.utils.libpc import crop_pc_2d, crop_pc_2d_index\n'), ((14689, 14743), 'torch.cat', 'torch.cat', (['[(min_bound + max_bound) / 2.0, z_shift]', '(0)'], {}), '([(min_bound + max_bound) / 2.0, z_shift], 0)\n', (14698, 14743), False, 'import torch\n'), ((14922, 14953), 'src.utils.libcoord.coord_transform.invert_transform', 'invert_transform', (['normalize_mat'], {}), '(normalize_mat)\n', (14938, 14953), False, 'from src.utils.libcoord.coord_transform import invert_transform, apply_transform\n'), ((15056, 15094), 'src.utils.libcoord.coord_transform.apply_transform', 'apply_transform', (['inputs', 'normalize_mat'], {}), '(inputs, normalize_mat)\n', (15071, 15094), False, 'from src.utils.libcoord.coord_transform import invert_transform, apply_transform\n'), ((15282, 15349), 'src.utils.libpc.crop_pc_2d', 'crop_pc_2d', (['inputs_norm', 'self._min_norm_bound', 'self._max_norm_bound'], {}), '(inputs_norm, self._min_norm_bound, self._max_norm_bound)\n', (15292, 15349), False, 'from src.utils.libpc import crop_pc_2d, crop_pc_2d_index\n'), ((946, 958), 'torch.eye', 'torch.eye', (['(4)'], {}), '(4)\n', (955, 958), False, 'import torch\n'), ((1328, 1340), 'torch.eye', 'torch.eye', (['(4)'], {}), '(4)\n', (1337, 1340), False, 'import torch\n'), ((3494, 3521), 'yaml.load', 'yaml.load', (['f'], {'Loader': 'Loader'}), '(f, Loader=Loader)\n', (3503, 3521), False, 'import yaml\n'), ((5083, 5146), 'torch.as_tensor', 'torch.as_tensor', (['self.images[0].pixel_size'], {'dtype': 'torch.float64'}), '(self.images[0].pixel_size, dtype=torch.float64)\n', (5098, 5146), False, 'import torch\n'), ((5773, 5810), 'os.path.join', 'os.path.join', (['dataset_dir', 'chunk_name'], {}), '(dataset_dir, chunk_name)\n', (5785, 5810), False, 'import os\n'), ((8093, 8164), 'logging.warning', 'logging.warning', (['"""random_length not provided when random_sample = True"""'], {}), "('random_length not provided when random_sample = True')\n", (8108, 8164), False, 'import logging\n'), ((10314, 10474), 'torch.tensor', 'torch.tensor', (['[self.patch_size[0] / (_x_range[1] - _x_range[0]), self.patch_size[1] / (\n _y_range[1] - _y_range[0]), self.z_std, 1]'], {'dtype': 'torch.float64'}), '([self.patch_size[0] / (_x_range[1] - _x_range[0]), self.\n patch_size[1] / (_y_range[1] - _y_range[0]), self.z_std, 1], dtype=\n torch.float64)\n', (10326, 10474), False, 'import torch\n'), ((11644, 11702), 'torch.tensor', 'torch.tensor', (["chunk_info['min_bound']"], {'dtype': 'torch.float64'}), "(chunk_info['min_bound'], dtype=torch.float64)\n", (11656, 11702), False, 'import torch\n'), ((11728, 11786), 'torch.tensor', 'torch.tensor', (["chunk_info['max_bound']"], {'dtype': 'torch.float64'}), "(chunk_info['max_bound'], dtype=torch.float64)\n", (11740, 11786), False, 'import torch\n'), ((11857, 11891), 'torch.rand', 'torch.rand', (['(2)'], {'dtype': 'torch.float64'}), '(2, dtype=torch.float64)\n', (11867, 11891), False, 'import torch\n'), ((13414, 13466), 'numpy.random.choice', 'np.random.choice', (['inputs.shape[0]', 'self._n_input_pts'], {}), '(inputs.shape[0], self._n_input_pts)\n', (13430, 13466), True, 'import numpy as np\n'), ((16000, 16057), 'src.utils.libpc.crop_pc_2d', 'crop_pc_2d', (["chunk_data['query_pts']", 'min_bound', 'max_bound'], {}), "(chunk_data['query_pts'], min_bound, max_bound)\n", (16010, 16057), False, 'from src.utils.libpc import crop_pc_2d, crop_pc_2d_index\n'), ((16252, 16290), 'src.utils.libcoord.coord_transform.apply_transform', 'apply_transform', (['points', 'normalize_mat'], {}), '(points, normalize_mat)\n', (16267, 16290), False, 'from src.utils.libcoord.coord_transform import invert_transform, apply_transform\n'), ((16489, 16562), 'src.utils.libpc.crop_pc_2d_index', 'crop_pc_2d_index', (['points_norm', 'self._min_norm_bound', 'self._max_norm_bound'], {}), '(points_norm, self._min_norm_bound, self._max_norm_bound)\n', (16505, 16562), False, 'from src.utils.libpc import crop_pc_2d, crop_pc_2d_index\n'), ((992, 1056), 'transformations.rotation_matrix', 'transformations.rotation_matrix', (['(-90.0 * math.pi / 180.0)', 'z_axis'], {}), '(-90.0 * math.pi / 180.0, z_axis)\n', (1023, 1056), False, 'import transformations\n'), ((1089, 1154), 'transformations.rotation_matrix', 'transformations.rotation_matrix', (['(-180.0 * math.pi / 180.0)', 'z_axis'], {}), '(-180.0 * math.pi / 180.0, z_axis)\n', (1120, 1154), False, 'import transformations\n'), ((1187, 1252), 'transformations.rotation_matrix', 'transformations.rotation_matrix', (['(-270.0 * math.pi / 180.0)', 'z_axis'], {}), '(-270.0 * math.pi / 180.0, z_axis)\n', (1218, 1252), False, 'import transformations\n'), ((1374, 1425), 'transformations.reflection_matrix', 'transformations.reflection_matrix', (['_origin', '_x_axis'], {}), '(_origin, _x_axis)\n', (1407, 1425), False, 'import transformations\n'), ((1493, 1544), 'transformations.reflection_matrix', 'transformations.reflection_matrix', (['_origin', '_y_axis'], {}), '(_origin, _y_axis)\n', (1526, 1544), False, 'import transformations\n'), ((3403, 3445), 'os.path.join', 'os.path.join', (['dataset_dir', 'self.CHUNK_INFO'], {}), '(dataset_dir, self.CHUNK_INFO)\n', (3415, 3445), False, 'import os\n'), ((3910, 3948), 'os.path.join', 'os.path.join', (['image_folder', 'image_name'], {}), '(image_folder, image_name)\n', (3922, 3948), False, 'import os\n'), ((3974, 3993), 'src.io.RasterIO.RasterReader', 'RasterReader', (['_path'], {}), '(_path)\n', (3986, 3993), False, 'from src.io.RasterIO import RasterReader, RasterData\n'), ((4053, 4107), 'logging.debug', 'logging.debug', (['f"""Satellite image loaded: {image_name}"""'], {}), "(f'Satellite image loaded: {image_name}')\n", (4066, 4107), False, 'import logging\n'), ((5868, 5921), 'os.path.join', 'os.path.join', (['chunk_full_path', 'self.INPUT_POINT_CLOUD'], {}), '(chunk_full_path, self.INPUT_POINT_CLOUD)\n', (5880, 5921), False, 'import os\n'), ((6999, 7030), 'numpy.concatenate', 'np.concatenate', (['query_pts_ls', '(0)'], {}), '(query_pts_ls, 0)\n', (7013, 7030), True, 'import numpy as np\n'), ((7071, 7102), 'numpy.concatenate', 'np.concatenate', (['query_occ_ls', '(0)'], {}), '(query_occ_ls, 0)\n', (7085, 7102), True, 'import numpy as np\n'), ((8775, 8808), 'numpy.array', 'np.array', (["chunk_info['min_bound']"], {}), "(chunk_info['min_bound'])\n", (8783, 8808), True, 'import numpy as np\n'), ((8841, 8874), 'numpy.array', 'np.array', (["chunk_info['max_bound']"], {}), "(chunk_info['max_bound'])\n", (8849, 8874), True, 'import numpy as np\n'), ((8967, 9066), 'numpy.arange', 'np.arange', (['_min_bound_np[0]', '(_max_bound_np[0] - self.patch_size[0])', 'self.slide_window_strip[0]'], {}), '(_min_bound_np[0], _max_bound_np[0] - self.patch_size[0], self.\n slide_window_strip[0])\n', (8976, 9066), True, 'import numpy as np\n'), ((9200, 9299), 'numpy.arange', 'np.arange', (['_min_bound_np[1]', '(_max_bound_np[1] - self.patch_size[1])', 'self.slide_window_strip[1]'], {}), '(_min_bound_np[1], _max_bound_np[1] - self.patch_size[1], self.\n slide_window_strip[1])\n', (9209, 9299), True, 'import numpy as np\n'), ((9488, 9523), 'numpy.meshgrid', 'np.meshgrid', (['patch_x_np', 'patch_y_np'], {}), '(patch_x_np, patch_y_np)\n', (9499, 9523), True, 'import numpy as np\n'), ((10653, 10689), 'torch.eye', 'torch.eye', (['(4)', '(3)'], {'dtype': 'torch.float64'}), '(4, 3, dtype=torch.float64)\n', (10662, 10689), False, 'import torch\n'), ((17043, 17099), 'numpy.random.choice', 'np.random.choice', (['points_idx.shape[0]', 'self._n_query_pts'], {}), '(points_idx.shape[0], self._n_query_pts)\n', (17059, 17099), True, 'import numpy as np\n'), ((18704, 18751), 'torch.Size', 'torch.Size', (['[self.n_images, shape[0], shape[1]]'], {}), '([self.n_images, shape[0], shape[1]])\n', (18714, 18751), False, 'import torch\n'), ((4404, 4442), 'torch.from_numpy', 'torch.from_numpy', (['_img_arr[None, :, :]'], {}), '(_img_arr[None, :, :])\n', (4420, 4442), False, 'import torch\n'), ((4493, 4514), 'torch.cat', 'torch.cat', (['temp_ls', '(0)'], {}), '(temp_ls, 0)\n', (4502, 4514), False, 'import torch\n'), ((5255, 5291), 'torch.floor', 'torch.floor', (['self._image_patch_shape'], {}), '(self._image_patch_shape)\n', (5266, 5291), False, 'import torch\n'), ((5436, 5472), 'torch.floor', 'torch.floor', (['self._image_patch_shape'], {}), '(self._image_patch_shape)\n', (5447, 5472), False, 'import torch\n'), ((6614, 6677), 'os.path.join', 'os.path.join', (['chunk_full_path', '(self.QUERY_POINTS % surface_type)'], {}), '(chunk_full_path, self.QUERY_POINTS % surface_type)\n', (6626, 6677), False, 'import os\n'), ((6708, 6726), 'numpy.load', 'np.load', (['file_path'], {}), '(file_path)\n', (6715, 6726), True, 'import numpy as np\n'), ((7155, 7186), 'numpy.concatenate', 'np.concatenate', (['masks_ls[_m]', '(0)'], {}), '(masks_ls[_m], 0)\n', (7169, 7186), True, 'import numpy as np\n'), ((12020, 12064), 'torch.floor', 'torch.floor', (['(anchor / self._image_pixel_size)'], {}), '(anchor / self._image_pixel_size)\n', (12031, 12064), False, 'import torch\n'), ((14857, 14888), 'src.utils.libcoord.coord_transform.invert_transform', 'invert_transform', (['transform_mat'], {}), '(transform_mat)\n', (14873, 14888), False, 'from src.utils.libcoord.coord_transform import invert_transform, apply_transform\n'), ((18785, 18832), 'torch.Size', 'torch.Size', (['[self.n_images, shape[0], shape[1]]'], {}), '([self.n_images, shape[0], shape[1]])\n', (18795, 18832), False, 'import torch\n'), ((6013, 6044), 'torch.from_numpy', 'torch.from_numpy', (["inputs['pts']"], {}), "(inputs['pts'])\n", (6029, 6044), False, 'import torch\n'), ((9119, 9168), 'numpy.array', 'np.array', (['[_max_bound_np[0] - self.patch_size[0]]'], {}), '([_max_bound_np[0] - self.patch_size[0]])\n', (9127, 9168), True, 'import numpy as np\n'), ((9352, 9401), 'numpy.array', 'np.array', (['[_max_bound_np[1] - self.patch_size[1]]'], {}), '([_max_bound_np[1] - self.patch_size[1]])\n', (9360, 9401), True, 'import numpy as np\n'), ((9638, 9663), 'torch.from_numpy', 'torch.from_numpy', (['anchors'], {}), '(anchors)\n', (9654, 9663), False, 'import torch\n'), ((10728, 10823), 'torch.tensor', 'torch.tensor', (['[(_x_range[1] - _x_range[0]) / 2.0, (_y_range[1] - _y_range[0]) / 2.0, 0, 1]'], {}), '([(_x_range[1] - _x_range[0]) / 2.0, (_y_range[1] - _y_range[0]\n ) / 2.0, 0, 1])\n', (10740, 10823), False, 'import torch\n'), ((12922, 12948), 'torch.median', 'torch.median', (['inputs[:, 2]'], {}), '(inputs[:, 2])\n', (12934, 12948), False, 'import torch\n'), ((7437, 7464), 'torch.from_numpy', 'torch.from_numpy', (['query_pts'], {}), '(query_pts)\n', (7453, 7464), False, 'import torch\n'), ((7508, 7535), 'torch.from_numpy', 'torch.from_numpy', (['query_occ'], {}), '(query_occ)\n', (7524, 7535), False, 'import torch\n'), ((7576, 7610), 'torch.from_numpy', 'torch.from_numpy', (["masks['mask_gt']"], {}), "(masks['mask_gt'])\n", (7592, 7610), False, 'import torch\n'), ((7656, 7696), 'torch.from_numpy', 'torch.from_numpy', (["masks['mask_building']"], {}), "(masks['mask_building'])\n", (7672, 7696), False, 'import torch\n'), ((7740, 7778), 'torch.from_numpy', 'torch.from_numpy', (["masks['mask_forest']"], {}), "(masks['mask_forest'])\n", (7756, 7778), False, 'import torch\n'), ((7821, 7858), 'torch.from_numpy', 'torch.from_numpy', (["masks['mask_water']"], {}), "(masks['mask_water'])\n", (7837, 7858), False, 'import torch\n'), ((13152, 13176), 'torch.mean', 'torch.mean', (['inputs[:, 2]'], {}), '(inputs[:, 2])\n', (13162, 13176), False, 'import torch\n')] |
#!/usr/bin/python
#-*- coding: utf-8 -*-
"""
This script contains util functions
"""
import warnings
warnings.filterwarnings('ignore')
import sys
import logging
logger = logging.getLogger(__name__)
logging.basicConfig(format='%(asctime)s : %(levelname)s : %(message)s', level=logging.INFO)
import numpy as np
from os.path import realpath
from scipy.spatial import distance
from sklearn import metrics
def combine(pair, df, mode='offset'):
# REMOVED FROM HERE
"""
Generates the training vectors from the input file
Parameters:
-----------
pairs: list
List containing tuples of pairs of norms and their class
df: pandas.dataframe
Dataframe containing embeddings
"""
emb1 = df.id2embed(pair[0])
emb2 = df.id2embed(pair[1])
if mode == 'offset':
comb = emb1 - emb2
elif mode == 'concat':
comb = np.concatenate((emb1,emb2))
elif mode == 'mean':
comb = (emb1 + emb2)/2.
elif mode == 'other':
off = emb1 - emb2
comb = np.concatenate((emb1,emb2,off))
else:
logger.error('Mode %s not implemented' % mode)
sys.exit(0)
return comb
def load_offset(offset_file):
""" Load the content of the offset file """
offset_file = realpath(offset_file)
return np.loadtxt(offset_file)
def cosine(v1, v2):
""" Calculate the cosine distance """
cos = distance.cosine(v1, v2)
return float(cos)
def euclidean(v1, v2):
""" Calculate the Euclidean distance """
euc = metrics.euclidean_distances([v1], [v2])
return float(euc[0][0])
def calculate_distance(v1, v2, measure='euc'):
""" Calculate distances between two vectors """
if not isinstance(v1, np.ndarray):
v1 = np.array(v1)
if not isinstance(v2, np.ndarray):
v1 = np.array(v2)
if measure == 'euc':
return euclidean(v1, v2)
elif measure == 'cos':
return cosine(v1, v2)
else:
logger.error('Measure %s not implemented!' % measure)
sys.exit(0)
def apply_metric(input_vector, metric, size, ids_only=True):
"""
Apply metric on an array. Allowed metrics include:
farthest: the highest distance to a point
closest: the lowest distance to a point
random: randomly selected elements
Parameters:
-----------
input_vector: array
list containing 3 elements each cell (distance, id_1, id_2),
where `distance` refers to the distance to a point
metric: string
name of the metric
size: int
size of the list in the output
ids_only: boolean
True to return (id_1, id_2)
False to return (distance, id_1, id_2)
Output:
-------
List containing `size` elements that belong to the metric
"""
vdist = []
if metric == 'farthest':
logger.debug('Applying FARTHEST metric on input')
vdist = sorted(input_vector, reverse=True)[:size]
elif metric == 'closest':
logger.debug('Applying CLOSEST metric on input')
vdist = sorted(input_vector)[:size]
elif metric == 'random':
logger.debug('Applying RANDOM metric on input')
vdist = np.random.sample(input_vector, size)
else:
logger.error('Metric %s not implemented' % metric)
sys.exit(0)
if ids_only:
vout = [(id1, id2) for _, id1, id2 in vdist]
else:
vout = [(id1, id2, val) for val, id1, id2 in vdist]
return vout
class KfoldResults(object):
def __init__(self, binary=True):
self.max_acc = 0
self.dresults = {}
self.binary = binary
def add(self, nb_fold, ground, predicted):
acc = metrics.accuracy_score(ground, predicted)
if self.binary:
prec, rec, fscore, _ = metrics.precision_recall_fscore_support(ground, predicted, average='binary')
else:
prec, rec, fscore, _ = metrics.precision_recall_fscore_support(ground, predicted)
prec = np.mean(np.array(prec))
rec = np.mean(np.array(rec))
fscore = np.mean(np.array(fscore))
self.dresults[nb_fold] = {
'accuracy': acc,
'precision': prec,
'recall': rec,
'f-score': fscore
}
def get_best(self, metric='accuracy'):
best_val = 0
best_fold = 0
for nb_fold in self.dresults:
if self.dresults[nb_fold].has_key(metric):
score = self.dresults[nb_fold][metric]
if score > best_val:
best_val = score
best_fold = nb_fold
else:
logger.error('Metric %s is not implemented' % metric)
sys.exit(0)
return best_fold, best_val
def add_mean(self):
""" Return the mean of each measure """
acc, prec, rec, fscore = 0, 0, 0, 0
for nb_fold in self.dresults:
acc += self.dresults[nb_fold]['accuracy']
prec += self.dresults[nb_fold]['precision']
rec += self.dresults[nb_fold]['recall']
fscore += self.dresults[nb_fold]['f-score']
mean_acc = float(acc)/len(self.dresults)
mean_prec = float(prec)/len(self.dresults)
mean_rec = float(rec)/len(self.dresults)
mean_fscore = float(fscore)/len(self.dresults)
self.dresults['mean'] = {
'accuracy': mean_acc,
'precision': mean_prec,
'recall': mean_rec,
'f-score': mean_fscore
}
return mean_acc, mean_prec, mean_rec, mean_fscore
def save(self, fname, show=True):
""" Save results in a file """
with open(fname, 'w') as fout:
for nb_fold in self.dresults:
fout.write('#Fold: %s\n' % str(nb_fold))
fout.write('- Accuracy: %f\n' % self.dresults[nb_fold]['accuracy'])
fout.write('- Precision: %f\n' % self.dresults[nb_fold]['precision'])
fout.write('- Recall: %f\n' % self.dresults[nb_fold]['recall'])
fout.write('- F-score: %f\n' % self.dresults[nb_fold]['f-score'])
if nb_fold == 'test' and show:
logger.info('> Fold: %s' % nb_fold)
logger.info('- Accuracy: %f' % self.dresults[nb_fold]['accuracy'])
logger.info('- Precision: %f' % self.dresults[nb_fold]['precision'])
logger.info('- Recall: %f' % self.dresults[nb_fold]['recall'])
logger.info('- F-score: %f' % self.dresults[nb_fold]['f-score'])
# End of class KfoldResults
| [
"scipy.spatial.distance.cosine",
"numpy.concatenate",
"logging.basicConfig",
"warnings.filterwarnings",
"os.path.realpath",
"sklearn.metrics.accuracy_score",
"sklearn.metrics.euclidean_distances",
"numpy.array",
"numpy.loadtxt",
"sys.exit",
"sklearn.metrics.precision_recall_fscore_support",
"l... | [((101, 134), 'warnings.filterwarnings', 'warnings.filterwarnings', (['"""ignore"""'], {}), "('ignore')\n", (124, 134), False, 'import warnings\n'), ((170, 197), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (187, 197), False, 'import logging\n'), ((198, 293), 'logging.basicConfig', 'logging.basicConfig', ([], {'format': '"""%(asctime)s : %(levelname)s : %(message)s"""', 'level': 'logging.INFO'}), "(format='%(asctime)s : %(levelname)s : %(message)s',\n level=logging.INFO)\n", (217, 293), False, 'import logging\n'), ((1257, 1278), 'os.path.realpath', 'realpath', (['offset_file'], {}), '(offset_file)\n', (1265, 1278), False, 'from os.path import realpath\n'), ((1290, 1313), 'numpy.loadtxt', 'np.loadtxt', (['offset_file'], {}), '(offset_file)\n', (1300, 1313), True, 'import numpy as np\n'), ((1388, 1411), 'scipy.spatial.distance.cosine', 'distance.cosine', (['v1', 'v2'], {}), '(v1, v2)\n', (1403, 1411), False, 'from scipy.spatial import distance\n'), ((1514, 1553), 'sklearn.metrics.euclidean_distances', 'metrics.euclidean_distances', (['[v1]', '[v2]'], {}), '([v1], [v2])\n', (1541, 1553), False, 'from sklearn import metrics\n'), ((1736, 1748), 'numpy.array', 'np.array', (['v1'], {}), '(v1)\n', (1744, 1748), True, 'import numpy as np\n'), ((1802, 1814), 'numpy.array', 'np.array', (['v2'], {}), '(v2)\n', (1810, 1814), True, 'import numpy as np\n'), ((3674, 3715), 'sklearn.metrics.accuracy_score', 'metrics.accuracy_score', (['ground', 'predicted'], {}), '(ground, predicted)\n', (3696, 3715), False, 'from sklearn import metrics\n'), ((874, 902), 'numpy.concatenate', 'np.concatenate', (['(emb1, emb2)'], {}), '((emb1, emb2))\n', (888, 902), True, 'import numpy as np\n'), ((2010, 2021), 'sys.exit', 'sys.exit', (['(0)'], {}), '(0)\n', (2018, 2021), False, 'import sys\n'), ((3775, 3851), 'sklearn.metrics.precision_recall_fscore_support', 'metrics.precision_recall_fscore_support', (['ground', 'predicted'], {'average': '"""binary"""'}), "(ground, predicted, average='binary')\n", (3814, 3851), False, 'from sklearn import metrics\n'), ((3901, 3959), 'sklearn.metrics.precision_recall_fscore_support', 'metrics.precision_recall_fscore_support', (['ground', 'predicted'], {}), '(ground, predicted)\n', (3940, 3959), False, 'from sklearn import metrics\n'), ((3181, 3217), 'numpy.random.sample', 'np.random.sample', (['input_vector', 'size'], {}), '(input_vector, size)\n', (3197, 3217), True, 'import numpy as np\n'), ((3295, 3306), 'sys.exit', 'sys.exit', (['(0)'], {}), '(0)\n', (3303, 3306), False, 'import sys\n'), ((3987, 4001), 'numpy.array', 'np.array', (['prec'], {}), '(prec)\n', (3995, 4001), True, 'import numpy as np\n'), ((4029, 4042), 'numpy.array', 'np.array', (['rec'], {}), '(rec)\n', (4037, 4042), True, 'import numpy as np\n'), ((4073, 4089), 'numpy.array', 'np.array', (['fscore'], {}), '(fscore)\n', (4081, 4089), True, 'import numpy as np\n'), ((4707, 4718), 'sys.exit', 'sys.exit', (['(0)'], {}), '(0)\n', (4715, 4718), False, 'import sys\n'), ((1026, 1059), 'numpy.concatenate', 'np.concatenate', (['(emb1, emb2, off)'], {}), '((emb1, emb2, off))\n', (1040, 1059), True, 'import numpy as np\n'), ((1131, 1142), 'sys.exit', 'sys.exit', (['(0)'], {}), '(0)\n', (1139, 1142), False, 'import sys\n')] |
import numpy as np
import itertools
from copy import deepcopy
from kimonet.utils import distance_vector_periodic
from kimonet.utils import get_supercell_increments
from kimonet.system.state import ground_state as _GS_
combinations_data = {}
def distance_matrix(molecules_list, supercell, max_distance=1):
# Set maximum possible distance everywhere
distances = np.ones((len(molecules_list), len(molecules_list))) * np.product(np.diag(supercell))
for i, mol_i in enumerate(molecules_list):
for j, mol_j in enumerate(molecules_list):
coordinates = mol_i.get_coordinates()
center_position = mol_j.get_coordinates()
cell_increments = get_supercell_increments(supercell, max_distance)
for cell_increment in cell_increments:
r_vec = distance_vector_periodic(coordinates - center_position, supercell, cell_increment)
d = np.linalg.norm(r_vec)
if distances[i, j] > d:
distances[i, j] = d
return distances
def is_connected(molecules_list, supercell, connected_distance=1):
# check if connected
for group in molecules_list:
d = distance_matrix(group, supercell, max_distance=connected_distance)
if len(d) > 1 and not np.all(connected_distance >= np.min(np.ma.masked_where(d == 0, d), axis=1)):
return False
return True
def is_connected_states(molecules_list, supercell, final_states):
# check if connected
for i, group in enumerate(molecules_list):
connected_distance = final_states[i].connected_distance
d = distance_matrix(group, supercell, max_distance=connected_distance)
if len(d) > 1 and not np.all(connected_distance >= np.min(np.ma.masked_where(d == 0, d), axis=1)):
return False
return True
def partition(elements_list, group_list):
partition = []
n = 0
for i in group_list:
partition.append(tuple(elements_list[n: n+i]))
n += i
return partition
def combinations_group(elements_list_o, process_final, supercell=None, include_self=True, ref_states=None):
group_list = tuple([s.size for s in process_final])
elements_list = tuple(range(len(elements_list_o)))
combinations_list = []
if (elements_list, group_list) not in combinations_data:
def combination(data_list, i, cumulative_list):
if i == 0:
cumulative_list = []
for data in itertools.combinations(data_list, group_list[i]):
rest = tuple(set(data_list) - set(data))
cumulative_list = cumulative_list[:i] + [data]
if len(rest) > 0:
combination(rest, i+1, deepcopy(cumulative_list))
else:
combinations_list.append(cumulative_list)
combination(elements_list, 0, [])
combinations_data[(elements_list, group_list)] = combinations_list
else:
combinations_list = combinations_data[(elements_list, group_list)]
# filter by connectivity
combinations_list = [[[elements_list_o[l] for l in state] for state in conf] for conf in combinations_list]
if supercell is not None:
for c in combinations_list:
if not is_connected_states(c, supercell, process_final):
combinations_list.remove(c)
if not include_self:
combinations_list = combinations_list[1:]
return combinations_list
def get_molecules_centered_in_mol(central_mol, molecules_list, supercell, size=1, connected_distance=2):
for c in itertools.combinations(molecules_list, size):
if central_mol in c and is_connected([c], supercell, connected_distance=connected_distance):
return list(c)
return None
if __name__ == '__main__':
from kimonet.system.state import State
from kimonet.system.molecule import Molecule
test_list = ['a', 'b', 'c']
group_list = [1, 2]
configuration = partition(test_list, group_list)
print(configuration)
combinations_list = combinations_group(test_list, group_list)
for c in combinations_list:
print(c, '---', configuration)
print(c == configuration)
print(c)
s1 = State(label='s1', energy=1.0, multiplicity=1)
molecule1 = Molecule(coordinates=[0])
molecule2 = Molecule(coordinates=[1])
molecule3 = Molecule(coordinates=[2])
molecule4 = Molecule(coordinates=[4])
supercell = [[6]]
test_list = [molecule1, molecule2, molecule3, molecule4]
group_list = [1, 3]
configuration = partition(test_list, group_list)
print('initial:', test_list)
combinations_list = combinations_group(test_list, group_list, supercell)
for c in combinations_list:
print('total: ', c)
a = distance_matrix(test_list, supercell, max_distance=1)
print(a)
print('centered:', molecule1)
mols = get_molecules_centered_in_mol(molecule1, test_list, supercell, size=3)
print('mols: ', mols)
exit()
| [
"copy.deepcopy",
"kimonet.system.molecule.Molecule",
"kimonet.system.state.State",
"numpy.ma.masked_where",
"kimonet.utils.distance_vector_periodic",
"itertools.combinations",
"numpy.linalg.norm",
"kimonet.utils.get_supercell_increments",
"numpy.diag"
] | [((3586, 3630), 'itertools.combinations', 'itertools.combinations', (['molecules_list', 'size'], {}), '(molecules_list, size)\n', (3608, 3630), False, 'import itertools\n'), ((4235, 4280), 'kimonet.system.state.State', 'State', ([], {'label': '"""s1"""', 'energy': '(1.0)', 'multiplicity': '(1)'}), "(label='s1', energy=1.0, multiplicity=1)\n", (4240, 4280), False, 'from kimonet.system.state import State\n'), ((4297, 4322), 'kimonet.system.molecule.Molecule', 'Molecule', ([], {'coordinates': '[0]'}), '(coordinates=[0])\n', (4305, 4322), False, 'from kimonet.system.molecule import Molecule\n'), ((4339, 4364), 'kimonet.system.molecule.Molecule', 'Molecule', ([], {'coordinates': '[1]'}), '(coordinates=[1])\n', (4347, 4364), False, 'from kimonet.system.molecule import Molecule\n'), ((4381, 4406), 'kimonet.system.molecule.Molecule', 'Molecule', ([], {'coordinates': '[2]'}), '(coordinates=[2])\n', (4389, 4406), False, 'from kimonet.system.molecule import Molecule\n'), ((4423, 4448), 'kimonet.system.molecule.Molecule', 'Molecule', ([], {'coordinates': '[4]'}), '(coordinates=[4])\n', (4431, 4448), False, 'from kimonet.system.molecule import Molecule\n'), ((437, 455), 'numpy.diag', 'np.diag', (['supercell'], {}), '(supercell)\n', (444, 455), True, 'import numpy as np\n'), ((691, 740), 'kimonet.utils.get_supercell_increments', 'get_supercell_increments', (['supercell', 'max_distance'], {}), '(supercell, max_distance)\n', (715, 740), False, 'from kimonet.utils import get_supercell_increments\n'), ((2478, 2526), 'itertools.combinations', 'itertools.combinations', (['data_list', 'group_list[i]'], {}), '(data_list, group_list[i])\n', (2500, 2526), False, 'import itertools\n'), ((816, 902), 'kimonet.utils.distance_vector_periodic', 'distance_vector_periodic', (['(coordinates - center_position)', 'supercell', 'cell_increment'], {}), '(coordinates - center_position, supercell,\n cell_increment)\n', (840, 902), False, 'from kimonet.utils import distance_vector_periodic\n'), ((919, 940), 'numpy.linalg.norm', 'np.linalg.norm', (['r_vec'], {}), '(r_vec)\n', (933, 940), True, 'import numpy as np\n'), ((2725, 2750), 'copy.deepcopy', 'deepcopy', (['cumulative_list'], {}), '(cumulative_list)\n', (2733, 2750), False, 'from copy import deepcopy\n'), ((1317, 1346), 'numpy.ma.masked_where', 'np.ma.masked_where', (['(d == 0)', 'd'], {}), '(d == 0, d)\n', (1335, 1346), True, 'import numpy as np\n'), ((1750, 1779), 'numpy.ma.masked_where', 'np.ma.masked_where', (['(d == 0)', 'd'], {}), '(d == 0, d)\n', (1768, 1779), True, 'import numpy as np\n')] |
#%%
import pandas as pd
import os.path
import numpy as np
#%%
DATA_DIR='Data'
sr_1_fn = os.path.join(DATA_DIR, 'sr_1.csv')
with open(sr_1_fn, encoding='cp950', errors='replace') as f:
df = pd.read_csv(f, nrows=10000000, usecols=['CUST_NO', 'TXN_DESC'])
#%%
df.head()
#%%
TXN = df.TXN_DESC.str.extract(r'([^\s0-9(512)]+)')
#%%
df.TXN_DESC.nunique()
#%%
df['TXN_DESC'] = TXN
#%%
df.TXN_DESC.nunique()
#%%
txn_counts = df.TXN_DESC.value_counts()
txn_counts.quantile(np.arange(.5,1,.01))
#%%
good_txn = txn_counts[txn_counts>100]
#df = df.loc[df.TXN_DESC.isin(good_txn.index)]
df.drop(df.loc[~df.TXN_DESC.isin(good_txn.index)].index, inplace=True)
df.TXN_DESC.nunique()
#%%
cust_counts = df.CUST_NO.value_counts()
cust_counts.quantile(np.arange(0,1,.01))
#%%
good_cust = cust_counts[cust_counts>120]
#df = df.loc[df.CUST_NO.isin(good_cust.index)]
df.drop(df.loc[~df.CUST_NO.isin(good_cust.index)].index, inplace=True)
#%%
df.TXN_DESC.nunique()
#%%
df.CUST_NO.nunique()
#%%
df = df.pivot_table(index='TXN_DESC', columns='CUST_NO', aggfunc=len, fill_value=0 )
#%%
def print_txn(n):
print(df.iloc[n].name)
#%%
print_txn(0)
#%%
from sklearn.decomposition import TruncatedSVD
SVD = TruncatedSVD(n_components=100)
matrix = SVD.fit_transform(df)
#%%
from sklearn.neighbors import NearestNeighbors
model_knn = NearestNeighbors(metric='correlation', algorithm='brute')
model_knn.fit(matrix)
#%%
def find_related(name):
i = df.index.get_loc(name)
distances, indices = model_knn.kneighbors(matrix[i:i+1], n_neighbors=6)
for i, d in zip(indices[0][1:], distances[0][1:]):
print(df.iloc[i].name, d)
#%%
find_related('台中新光影城')
#%%
find_related('友邦人壽')
#%%
find_related('AGODA')
#%%
find_related('一卡通自動加值')
#%%
find_related('中友百貨公司')
#%%
| [
"pandas.read_csv",
"numpy.arange",
"sklearn.neighbors.NearestNeighbors",
"sklearn.decomposition.TruncatedSVD"
] | [((1191, 1221), 'sklearn.decomposition.TruncatedSVD', 'TruncatedSVD', ([], {'n_components': '(100)'}), '(n_components=100)\n', (1203, 1221), False, 'from sklearn.decomposition import TruncatedSVD\n'), ((1317, 1374), 'sklearn.neighbors.NearestNeighbors', 'NearestNeighbors', ([], {'metric': '"""correlation"""', 'algorithm': '"""brute"""'}), "(metric='correlation', algorithm='brute')\n", (1333, 1374), False, 'from sklearn.neighbors import NearestNeighbors\n'), ((193, 256), 'pandas.read_csv', 'pd.read_csv', (['f'], {'nrows': '(10000000)', 'usecols': "['CUST_NO', 'TXN_DESC']"}), "(f, nrows=10000000, usecols=['CUST_NO', 'TXN_DESC'])\n", (204, 256), True, 'import pandas as pd\n'), ((471, 494), 'numpy.arange', 'np.arange', (['(0.5)', '(1)', '(0.01)'], {}), '(0.5, 1, 0.01)\n', (480, 494), True, 'import numpy as np\n'), ((739, 760), 'numpy.arange', 'np.arange', (['(0)', '(1)', '(0.01)'], {}), '(0, 1, 0.01)\n', (748, 760), True, 'import numpy as np\n')] |
import pandas as pd
import pygal
from pygal.style import DefaultStyle
import numpy as np
from sklearn.linear_model import LinearRegression
from sklearn.preprocessing import PolynomialFeatures
from iso3166 import countries
from pygal.style import RotateStyle
paths={'cw':'static/cases_worldwide.svg',
'ci':'static/cases_india.svg',
'pr':'static/prediction_india.svg',
'ttpos':'static/test_to_positive_stacked.svg',
'mf':'static/male_female.svg',
'sttst':'static/state_wise_testing_radar.svg',
'world':'static/world_map.svg',
'guj':'static/guj.svg',
'guj2':'static/guj2.svg',
'ic':'static/ind_cases.svg',
'ir':'static/ind_recovered.svg',
'id':'static/ind_dead.svg',
'piei':'static/piechart_india.svg',
'pieg':'static/piechart_guj.svg'
}
def plot_cases_worldwide(df,path):
start_date = df.head(1).date.values[0]
end_date = df.tail(1).date.values[0]
daterange = pd.date_range(start_date, end_date)
dates = []
cases = []
deaths = []
for single_date in daterange:
d = single_date.strftime("%Y-%m-%d")
dates.append(d)
temp = df[df['date'] == d]
case = temp['total_cases'].values[0]
death = temp['total_deaths'].values[0]
cases.append(case)
deaths.append(death)
line_chart = pygal.Line(fill=True,show_legend=True,show_x_labels=True, show_y_labels=True, style=DefaultStyle)
line_chart.add('Cases', cases, show_dots=True,dots_size=8)
line_chart.add('Deaths', deaths, show_dots=True,dots_size=8)
line_chart.x_labels = map(str, dates)
line_chart.render_to_file(path)
def plot_cases_india(df,path):
dates = []
cases = []
deaths = []
recovered=[]
for i in range(len(df)):
dates.append(df.iloc[i].values[0])
cases.append(df.iloc[i].values[2])
deaths.append(df.iloc[i].values[6])
recovered.append(df.iloc[i].values[4])
line_chart = pygal.Line(fill=True,show_legend=True, show_x_labels=True, show_y_labels=False, style=DefaultStyle)
line_chart.add('Cases', cases, show_dots=True,dots_size=8)
line_chart.add('Recovered', recovered, show_dots=True,dots_size=8)
line_chart.add('Deaths', deaths, show_dots=True,dots_size=8)
line_chart.x_labels = map(str, dates)
line_chart.render_to_file(path)
return cases,deaths,recovered
def plot_prediction_india(cases,deaths,path):
dates=[i+1 for i in range(len(cases))]
X = np.array(dates[-10:])
Y = np.log(cases[-10:])
Z = np.log(deaths[-10:])
X = X[:, np.newaxis]
lin_reg_cases= LinearRegression()
lin_reg_cases.fit(X, Y)
lin_reg_deaths = LinearRegression()
lin_reg_deaths.fit(X, Z)
line_chart = pygal.Line(fill=False, show_legend=False, show_x_labels=True, show_y_labels=False, style=DefaultStyle)
line_chart.x_labels = map(str, ['Yesterday','Today','Tommorow','Day-After'])
line_chart.add('Cases',[np.exp(lin_reg_cases.predict([[dates[-2]]])[0]),
np.exp(lin_reg_cases.predict([[dates[-1]]])[0]),
np.exp(lin_reg_cases.predict([[dates[-1]+1]])[0]),
np.exp(lin_reg_cases.predict([[dates[-1]+2]])[0])],show_dots=True,dots_size=15)
line_chart.add('Deaths',
[np.exp(lin_reg_deaths.predict([[dates[-2]]])[0]),
np.exp(lin_reg_deaths.predict([[dates[-1]]])[0]),
np.exp(lin_reg_deaths.predict([[dates[-1] + 1]])[0]),
np.exp(lin_reg_deaths.predict([[dates[-1] + 2]])[0])], show_dots=True,dots_size=15)
line_chart.render_to_file(path)
def testing_findings(df,df2,path):
tests = []
cases = []
states = []
for state in df.State.unique():
temp = df[df['State'] == state]
if len(temp)>2:
if temp.tail(1).isnull().values[0][2]:
temp = temp.iloc[-2]
else:
temp = temp.iloc[-1]
states.append(state)
tests.append(temp.values[2])
cases.append(temp.values[3])
ratio=[]
for i in range(len(cases)):
if tests[i] != np.nan and cases[i] !=np.nan:
ratio.append(int(100*tests[i]/cases[i]))
line_chart = pygal.Bar()
line_chart.title = 'Statewise calculation'
line_chart.x_labels = map(str, states)
line_chart.add('Test',tests)
line_chart.add('Cases',cases)
line_chart.add('Test Positive Per 100',ratio)
line_chart.render_table(style=True)
def plot_male_female(df,path):
g=df.Gender.value_counts()
Male=g.values[0]
Female = g.values[1]
tot=Male+Female
Male=100*Male/tot
Female=100*Female/tot
pie_chart = pygal.Pie(inner_radius=.4)
pie_chart.title = 'Male vs Female affected becaues of COVID-19'
pie_chart.add('Male', Male)
pie_chart.add('Female', Female)
pie_chart.render_to_file(path)
def plot_world_map(df,path):
world_dict={}
for c in countries:
try:
world_dict[str(c.alpha2).lower()]=df[df['iso_code'] ==str(c.alpha3).upper()].iloc[-1][3]
except:
world_dict[str(c.alpha2).lower()]=0
worldmap_chart = pygal.maps.world.World(style=RotateStyle('#336699'))
worldmap_chart.force_uri_protocol = "http"
worldmap_chart.value_formatter = lambda x: "{:,}".format(x)
worldmap_chart.value_formatter = lambda y: "{:,}".format(y)
worldmap_chart.title = 'Covid 19 stats'
worldmap_chart.add('COVID-19', world_dict)
worldmap_chart.render_to_file(path)
def plot_guj_1(df):
t=df['Detected District'].value_counts()[:10]
line_chart = pygal.HorizontalBar()
line_chart.title = 'Cities with Highest Cases'
for i in range(len(t)):
line_chart.add(t.index[i],t[i])
line_chart.render_to_file(paths['guj'])
def plot_cases_rec_ded_state(df,ttt):
daterange = pd.date_range(df.Date[0], df.iloc[-1].values[0])
line_chart1 = pygal.Line()
line_chart2 = pygal.Line()
line_chart3 = pygal.Line()
line_chart3.title = 'Recovered'
line_chart2.title = 'Deaths'
line_chart1.title = 'Cases'
line_chart4 = pygal.Line(fill=True)
line_chart4.title = 'Gujarat COVID-19'
ttt = pd.read_csv('stats/state_wise.csv')
for i in range(len(df.columns) - 3):
dates = []
cases = []
recovered = []
deaths = []
state = df.columns[3 + i]
for single_date in daterange:
d = single_date.strftime("%d-%b-%y")
dates.append(d)
temp = df[df['Date'] == d]
case = temp[state].values[0]
death = temp[state].values[2]
rec = temp[state].values[1]
cases.append(case)
deaths.append(death)
recovered.append(rec)
line_chart3.add(ttt[ttt['State_code'] == state]['State'].values[0], recovered, dots_size=1)
line_chart2.add(ttt[ttt['State_code'] == state]['State'].values[0], deaths, dots_size=1)
line_chart1.add(ttt[ttt['State_code'] == state]['State'].values[0], cases, dots_size=1)
line_chart1.x_labels = map(str, dates)
line_chart2.x_labels = map(str, dates)
line_chart3.x_labels = map(str, dates)
if (state == 'GJ'):
line_chart4.add("Cases", cases)
line_chart4.add("Recovered", recovered)
line_chart4.add("Deaths", deaths)
line_chart4.x_labels = map(str, dates)
line_chart1.render_to_file(paths['ic'])
line_chart2.render_to_file(paths['id'])
line_chart3.render_to_file(paths['ir'])
line_chart4.render_to_file(paths['guj2'])
def plot_spread_pie(df,df_guj):
t=df['Type of transmission'].value_counts()
pie_chart = pygal.Pie()
pie_chart.title = 'Transmission type (TBD-To Be Decided)*(for Available data)'
pie_chart.add(t.index[0], t[0])
pie_chart.add(t.index[1], t[1])
pie_chart.add(t.index[2], t[2])
pie_chart.render_to_file(paths['piei'])
t = df_guj['Type of transmission'].value_counts()
pie_chart = pygal.Pie()
pie_chart.title = 'Transmission type (TBD-To Be Decided)*(for Available data)'
pie_chart.add(t.index[0], t[0])
pie_chart.add(t.index[1], t[1])
pie_chart.add(t.index[2], t[2])
pie_chart.render_to_file(paths['pieg'])
if __name__=='__main__':
raw_data=pd.read_csv('stats/raw_data.csv')
state_wise=pd.read_csv('stats/state_wise.csv')
state_wise_daily=pd.read_csv('stats/state_wise_daily.csv')
statewise_tested_numbers_data=pd.read_csv('stats/statewise_tested_numbers_data.csv')
case_time_series=pd.read_csv('stats/case_time_series.csv')
tested_numbers_icmr_data=pd.read_csv('stats/tested_numbers_icmr_data.csv')
world_cases=pd.read_csv('stats/world_cases.csv')
world_cases_all=pd.read_csv('stats/world_all_cases.csv')
guj=pd.read_csv('stats/gujarat.csv')
plot_cases_worldwide(world_cases,paths['cw'])
cases,deaths,recovered=plot_cases_india(case_time_series,paths['ci'])
plot_prediction_india(cases,deaths,paths['pr'])
#testing_findings(statewise_tested_numbers_data,state_wise,paths['ttpos'])
plot_male_female(raw_data,paths['mf'])
plot_world_map(world_cases_all,paths['world'])
plot_guj_1(guj)
plot_cases_rec_ded_state(state_wise_daily,state_wise)
plot_spread_pie(raw_data,guj)
| [
"pygal.Pie",
"pandas.date_range",
"numpy.log",
"pandas.read_csv",
"pygal.HorizontalBar",
"pygal.Line",
"pygal.Bar",
"sklearn.linear_model.LinearRegression",
"pygal.style.RotateStyle",
"numpy.array"
] | [((972, 1007), 'pandas.date_range', 'pd.date_range', (['start_date', 'end_date'], {}), '(start_date, end_date)\n', (985, 1007), True, 'import pandas as pd\n'), ((1359, 1463), 'pygal.Line', 'pygal.Line', ([], {'fill': '(True)', 'show_legend': '(True)', 'show_x_labels': '(True)', 'show_y_labels': '(True)', 'style': 'DefaultStyle'}), '(fill=True, show_legend=True, show_x_labels=True, show_y_labels=\n True, style=DefaultStyle)\n', (1369, 1463), False, 'import pygal\n'), ((1981, 2086), 'pygal.Line', 'pygal.Line', ([], {'fill': '(True)', 'show_legend': '(True)', 'show_x_labels': '(True)', 'show_y_labels': '(False)', 'style': 'DefaultStyle'}), '(fill=True, show_legend=True, show_x_labels=True, show_y_labels=\n False, style=DefaultStyle)\n', (1991, 2086), False, 'import pygal\n'), ((2490, 2511), 'numpy.array', 'np.array', (['dates[-10:]'], {}), '(dates[-10:])\n', (2498, 2511), True, 'import numpy as np\n'), ((2520, 2539), 'numpy.log', 'np.log', (['cases[-10:]'], {}), '(cases[-10:])\n', (2526, 2539), True, 'import numpy as np\n'), ((2548, 2568), 'numpy.log', 'np.log', (['deaths[-10:]'], {}), '(deaths[-10:])\n', (2554, 2568), True, 'import numpy as np\n'), ((2613, 2631), 'sklearn.linear_model.LinearRegression', 'LinearRegression', ([], {}), '()\n', (2629, 2631), False, 'from sklearn.linear_model import LinearRegression\n'), ((2681, 2699), 'sklearn.linear_model.LinearRegression', 'LinearRegression', ([], {}), '()\n', (2697, 2699), False, 'from sklearn.linear_model import LinearRegression\n'), ((2746, 2853), 'pygal.Line', 'pygal.Line', ([], {'fill': '(False)', 'show_legend': '(False)', 'show_x_labels': '(True)', 'show_y_labels': '(False)', 'style': 'DefaultStyle'}), '(fill=False, show_legend=False, show_x_labels=True, show_y_labels\n =False, style=DefaultStyle)\n', (2756, 2853), False, 'import pygal\n'), ((4262, 4273), 'pygal.Bar', 'pygal.Bar', ([], {}), '()\n', (4271, 4273), False, 'import pygal\n'), ((4714, 4741), 'pygal.Pie', 'pygal.Pie', ([], {'inner_radius': '(0.4)'}), '(inner_radius=0.4)\n', (4723, 4741), False, 'import pygal\n'), ((5630, 5651), 'pygal.HorizontalBar', 'pygal.HorizontalBar', ([], {}), '()\n', (5649, 5651), False, 'import pygal\n'), ((5870, 5918), 'pandas.date_range', 'pd.date_range', (['df.Date[0]', 'df.iloc[-1].values[0]'], {}), '(df.Date[0], df.iloc[-1].values[0])\n', (5883, 5918), True, 'import pandas as pd\n'), ((5937, 5949), 'pygal.Line', 'pygal.Line', ([], {}), '()\n', (5947, 5949), False, 'import pygal\n'), ((5968, 5980), 'pygal.Line', 'pygal.Line', ([], {}), '()\n', (5978, 5980), False, 'import pygal\n'), ((5999, 6011), 'pygal.Line', 'pygal.Line', ([], {}), '()\n', (6009, 6011), False, 'import pygal\n'), ((6131, 6152), 'pygal.Line', 'pygal.Line', ([], {'fill': '(True)'}), '(fill=True)\n', (6141, 6152), False, 'import pygal\n'), ((6206, 6241), 'pandas.read_csv', 'pd.read_csv', (['"""stats/state_wise.csv"""'], {}), "('stats/state_wise.csv')\n", (6217, 6241), True, 'import pandas as pd\n'), ((7703, 7714), 'pygal.Pie', 'pygal.Pie', ([], {}), '()\n', (7712, 7714), False, 'import pygal\n'), ((8020, 8031), 'pygal.Pie', 'pygal.Pie', ([], {}), '()\n', (8029, 8031), False, 'import pygal\n'), ((8309, 8342), 'pandas.read_csv', 'pd.read_csv', (['"""stats/raw_data.csv"""'], {}), "('stats/raw_data.csv')\n", (8320, 8342), True, 'import pandas as pd\n'), ((8358, 8393), 'pandas.read_csv', 'pd.read_csv', (['"""stats/state_wise.csv"""'], {}), "('stats/state_wise.csv')\n", (8369, 8393), True, 'import pandas as pd\n'), ((8415, 8456), 'pandas.read_csv', 'pd.read_csv', (['"""stats/state_wise_daily.csv"""'], {}), "('stats/state_wise_daily.csv')\n", (8426, 8456), True, 'import pandas as pd\n'), ((8491, 8545), 'pandas.read_csv', 'pd.read_csv', (['"""stats/statewise_tested_numbers_data.csv"""'], {}), "('stats/statewise_tested_numbers_data.csv')\n", (8502, 8545), True, 'import pandas as pd\n'), ((8567, 8608), 'pandas.read_csv', 'pd.read_csv', (['"""stats/case_time_series.csv"""'], {}), "('stats/case_time_series.csv')\n", (8578, 8608), True, 'import pandas as pd\n'), ((8638, 8687), 'pandas.read_csv', 'pd.read_csv', (['"""stats/tested_numbers_icmr_data.csv"""'], {}), "('stats/tested_numbers_icmr_data.csv')\n", (8649, 8687), True, 'import pandas as pd\n'), ((8704, 8740), 'pandas.read_csv', 'pd.read_csv', (['"""stats/world_cases.csv"""'], {}), "('stats/world_cases.csv')\n", (8715, 8740), True, 'import pandas as pd\n'), ((8761, 8801), 'pandas.read_csv', 'pd.read_csv', (['"""stats/world_all_cases.csv"""'], {}), "('stats/world_all_cases.csv')\n", (8772, 8801), True, 'import pandas as pd\n'), ((8810, 8842), 'pandas.read_csv', 'pd.read_csv', (['"""stats/gujarat.csv"""'], {}), "('stats/gujarat.csv')\n", (8821, 8842), True, 'import pandas as pd\n'), ((5212, 5234), 'pygal.style.RotateStyle', 'RotateStyle', (['"""#336699"""'], {}), "('#336699')\n", (5223, 5234), False, 'from pygal.style import RotateStyle\n')] |
import asyncio
import sys
import numpy as np
import pytest
import ucp
async def shutdown(ep):
await ep.close()
@pytest.mark.asyncio
async def test_server_shutdown():
"""The server calls shutdown"""
async def server_node(ep):
msg = np.empty(10 ** 6)
with pytest.raises(ucp.exceptions.UCXCanceled):
await asyncio.gather(ep.recv(msg), shutdown(ep))
async def client_node(port):
ep = await ucp.create_endpoint(ucp.get_address(), port)
msg = np.empty(10 ** 6)
with pytest.raises(ucp.exceptions.UCXCanceled):
await ep.recv(msg)
listener = ucp.create_listener(server_node)
await client_node(listener.port)
@pytest.mark.skipif(
sys.version_info < (3, 7), reason="test currently fails for python3.6"
)
@pytest.mark.asyncio
async def test_client_shutdown():
"""The client calls shutdown"""
async def client_node(port):
ep = await ucp.create_endpoint(ucp.get_address(), port)
msg = np.empty(10 ** 6)
with pytest.raises(ucp.exceptions.UCXCanceled):
await asyncio.gather(ep.recv(msg), shutdown(ep))
async def server_node(ep):
msg = np.empty(10 ** 6)
with pytest.raises(ucp.exceptions.UCXCanceled):
await ep.recv(msg)
listener = ucp.create_listener(server_node)
await client_node(listener.port)
@pytest.mark.asyncio
async def test_listener_close():
"""The server close the listener"""
async def client_node(listener):
ep = await ucp.create_endpoint(ucp.get_address(), listener.port)
msg = np.empty(100, dtype=np.int64)
await ep.recv(msg)
await ep.recv(msg)
assert listener.closed() is False
listener.close()
assert listener.closed() is True
async def server_node(ep):
await ep.send(np.arange(100, dtype=np.int64))
await ep.send(np.arange(100, dtype=np.int64))
listener = ucp.create_listener(server_node)
await client_node(listener)
@pytest.mark.asyncio
async def test_listener_del():
"""The client delete the listener"""
async def server_node(ep):
await ep.send(np.arange(100, dtype=np.int64))
await ep.send(np.arange(100, dtype=np.int64))
listener = ucp.create_listener(server_node)
ep = await ucp.create_endpoint(ucp.get_address(), listener.port)
msg = np.empty(100, dtype=np.int64)
await ep.recv(msg)
assert listener.closed() is False
del listener
await ep.recv(msg)
@pytest.mark.asyncio
async def test_close_after_n_recv():
"""The Endpoint.close_after_n_recv()"""
async def server_node(ep):
for _ in range(10):
await ep.send(np.arange(10))
async def client_node(port):
ep = await ucp.create_endpoint(ucp.get_address(), port)
ep.close_after_n_recv(10)
for _ in range(10):
msg = np.empty(10)
await ep.recv(msg)
assert ep.closed()
ep = await ucp.create_endpoint(ucp.get_address(), port)
for _ in range(5):
msg = np.empty(10)
await ep.recv(msg)
ep.close_after_n_recv(5)
for _ in range(5):
msg = np.empty(10)
await ep.recv(msg)
assert ep.closed()
ep = await ucp.create_endpoint(ucp.get_address(), port)
for _ in range(5):
msg = np.empty(10)
await ep.recv(msg)
ep.close_after_n_recv(10, count_from_ep_creation=True)
for _ in range(5):
msg = np.empty(10)
await ep.recv(msg)
assert ep.closed()
ep = await ucp.create_endpoint(ucp.get_address(), port)
for _ in range(10):
msg = np.empty(10)
await ep.recv(msg)
with pytest.raises(
ucp.exceptions.UCXError, match="`n` cannot be less than current recv_count"
):
ep.close_after_n_recv(5, count_from_ep_creation=True)
ep.close_after_n_recv(1)
with pytest.raises(
ucp.exceptions.UCXError, match="close_after_n_recv has already been set to"
):
ep.close_after_n_recv(1)
listener = ucp.create_listener(server_node)
await client_node(listener.port)
| [
"numpy.empty",
"pytest.raises",
"ucp.create_listener",
"pytest.mark.skipif",
"ucp.get_address",
"numpy.arange"
] | [((699, 794), 'pytest.mark.skipif', 'pytest.mark.skipif', (['(sys.version_info < (3, 7))'], {'reason': '"""test currently fails for python3.6"""'}), "(sys.version_info < (3, 7), reason=\n 'test currently fails for python3.6')\n", (717, 794), False, 'import pytest\n'), ((626, 658), 'ucp.create_listener', 'ucp.create_listener', (['server_node'], {}), '(server_node)\n', (645, 658), False, 'import ucp\n'), ((1301, 1333), 'ucp.create_listener', 'ucp.create_listener', (['server_node'], {}), '(server_node)\n', (1320, 1333), False, 'import ucp\n'), ((1940, 1972), 'ucp.create_listener', 'ucp.create_listener', (['server_node'], {}), '(server_node)\n', (1959, 1972), False, 'import ucp\n'), ((2256, 2288), 'ucp.create_listener', 'ucp.create_listener', (['server_node'], {}), '(server_node)\n', (2275, 2288), False, 'import ucp\n'), ((2368, 2397), 'numpy.empty', 'np.empty', (['(100)'], {'dtype': 'np.int64'}), '(100, dtype=np.int64)\n', (2376, 2397), True, 'import numpy as np\n'), ((4152, 4184), 'ucp.create_listener', 'ucp.create_listener', (['server_node'], {}), '(server_node)\n', (4171, 4184), False, 'import ucp\n'), ((258, 275), 'numpy.empty', 'np.empty', (['(10 ** 6)'], {}), '(10 ** 6)\n', (266, 275), True, 'import numpy as np\n'), ((505, 522), 'numpy.empty', 'np.empty', (['(10 ** 6)'], {}), '(10 ** 6)\n', (513, 522), True, 'import numpy as np\n'), ((999, 1016), 'numpy.empty', 'np.empty', (['(10 ** 6)'], {}), '(10 ** 6)\n', (1007, 1016), True, 'import numpy as np\n'), ((1180, 1197), 'numpy.empty', 'np.empty', (['(10 ** 6)'], {}), '(10 ** 6)\n', (1188, 1197), True, 'import numpy as np\n'), ((1592, 1621), 'numpy.empty', 'np.empty', (['(100)'], {'dtype': 'np.int64'}), '(100, dtype=np.int64)\n', (1600, 1621), True, 'import numpy as np\n'), ((289, 330), 'pytest.raises', 'pytest.raises', (['ucp.exceptions.UCXCanceled'], {}), '(ucp.exceptions.UCXCanceled)\n', (302, 330), False, 'import pytest\n'), ((536, 577), 'pytest.raises', 'pytest.raises', (['ucp.exceptions.UCXCanceled'], {}), '(ucp.exceptions.UCXCanceled)\n', (549, 577), False, 'import pytest\n'), ((1030, 1071), 'pytest.raises', 'pytest.raises', (['ucp.exceptions.UCXCanceled'], {}), '(ucp.exceptions.UCXCanceled)\n', (1043, 1071), False, 'import pytest\n'), ((1211, 1252), 'pytest.raises', 'pytest.raises', (['ucp.exceptions.UCXCanceled'], {}), '(ucp.exceptions.UCXCanceled)\n', (1224, 1252), False, 'import pytest\n'), ((2324, 2341), 'ucp.get_address', 'ucp.get_address', ([], {}), '()\n', (2339, 2341), False, 'import ucp\n'), ((2882, 2894), 'numpy.empty', 'np.empty', (['(10)'], {}), '(10)\n', (2890, 2894), True, 'import numpy as np\n'), ((3063, 3075), 'numpy.empty', 'np.empty', (['(10)'], {}), '(10)\n', (3071, 3075), True, 'import numpy as np\n'), ((3185, 3197), 'numpy.empty', 'np.empty', (['(10)'], {}), '(10)\n', (3193, 3197), True, 'import numpy as np\n'), ((3366, 3378), 'numpy.empty', 'np.empty', (['(10)'], {}), '(10)\n', (3374, 3378), True, 'import numpy as np\n'), ((3518, 3530), 'numpy.empty', 'np.empty', (['(10)'], {}), '(10)\n', (3526, 3530), True, 'import numpy as np\n'), ((3700, 3712), 'numpy.empty', 'np.empty', (['(10)'], {}), '(10)\n', (3708, 3712), True, 'import numpy as np\n'), ((3758, 3853), 'pytest.raises', 'pytest.raises', (['ucp.exceptions.UCXError'], {'match': '"""`n` cannot be less than current recv_count"""'}), "(ucp.exceptions.UCXError, match=\n '`n` cannot be less than current recv_count')\n", (3771, 3853), False, 'import pytest\n'), ((3985, 4080), 'pytest.raises', 'pytest.raises', (['ucp.exceptions.UCXError'], {'match': '"""close_after_n_recv has already been set to"""'}), "(ucp.exceptions.UCXError, match=\n 'close_after_n_recv has already been set to')\n", (3998, 4080), False, 'import pytest\n'), ((466, 483), 'ucp.get_address', 'ucp.get_address', ([], {}), '()\n', (481, 483), False, 'import ucp\n'), ((960, 977), 'ucp.get_address', 'ucp.get_address', ([], {}), '()\n', (975, 977), False, 'import ucp\n'), ((1544, 1561), 'ucp.get_address', 'ucp.get_address', ([], {}), '()\n', (1559, 1561), False, 'import ucp\n'), ((1838, 1868), 'numpy.arange', 'np.arange', (['(100)'], {'dtype': 'np.int64'}), '(100, dtype=np.int64)\n', (1847, 1868), True, 'import numpy as np\n'), ((1892, 1922), 'numpy.arange', 'np.arange', (['(100)'], {'dtype': 'np.int64'}), '(100, dtype=np.int64)\n', (1901, 1922), True, 'import numpy as np\n'), ((2154, 2184), 'numpy.arange', 'np.arange', (['(100)'], {'dtype': 'np.int64'}), '(100, dtype=np.int64)\n', (2163, 2184), True, 'import numpy as np\n'), ((2208, 2238), 'numpy.arange', 'np.arange', (['(100)'], {'dtype': 'np.int64'}), '(100, dtype=np.int64)\n', (2217, 2238), True, 'import numpy as np\n'), ((2777, 2794), 'ucp.get_address', 'ucp.get_address', ([], {}), '()\n', (2792, 2794), False, 'import ucp\n'), ((2993, 3010), 'ucp.get_address', 'ucp.get_address', ([], {}), '()\n', (3008, 3010), False, 'import ucp\n'), ((3296, 3313), 'ucp.get_address', 'ucp.get_address', ([], {}), '()\n', (3311, 3313), False, 'import ucp\n'), ((3629, 3646), 'ucp.get_address', 'ucp.get_address', ([], {}), '()\n', (3644, 3646), False, 'import ucp\n'), ((2689, 2702), 'numpy.arange', 'np.arange', (['(10)'], {}), '(10)\n', (2698, 2702), True, 'import numpy as np\n')] |
import os
import random
import numpy as np
from scipy.ndimage import zoom
from collections import defaultdict
import cv2
DATA_MEAN = np.array([[[123.68, 116.779, 103.939]]])
def preprocess_img(img, input_shape):
img = cv2.resize(img, input_shape)
img = img - DATA_MEAN
img = img[:, :, ::-1]
img.astype('float32')
return img
def update_inputs(batch_size=None, input_size=None, num_classes=None):
return np.zeros([batch_size, input_size[0], input_size[1], 3]), \
np.zeros([batch_size, input_size[0], input_size[1], num_classes])
def data_generator_s31(datadir='', nb_classes=None, batch_size=None, input_size=None, separator='_', test_nmb=50):
if not os.path.exists(datadir):
print("ERROR!The folder is not exist")
# listdir = os.listdir(datadir)
data = defaultdict(dict)
image_dir = os.path.join(datadir, "imgs")
image_paths = os.listdir(image_dir)
for image_path in image_paths:
nmb = image_path.split(separator)[0]
data[nmb]['image'] = image_path
anno_dir = os.path.join(datadir, "maps_bordered")
anno_paths = os.listdir(anno_dir)
for anno_path in anno_paths:
nmb = anno_path.split(separator)[0]
data[nmb]['anno'] = anno_path
values = data.values()
random.shuffle(values)
return generate(values[test_nmb:], nb_classes, batch_size, input_size, image_dir, anno_dir), \
generate(values[:test_nmb], nb_classes, batch_size, input_size, image_dir, anno_dir)
def generate(values, nb_classes, batch_size, input_size, image_dir, anno_dir):
while 1:
random.shuffle(values)
images, labels = update_inputs(batch_size=batch_size,
input_size=input_size, num_classes=nb_classes)
for i, d in enumerate(values):
img = cv2.imread(os.path.join(image_dir, d['image']))[:, :, ::-1] # Read RGB
img = cv2.resize(img, input_size)
y = cv2.imread(os.path.join(anno_dir, d['anno']), cv2.IMREAD_GRAYSCALE)
h, w = input_size
y = zoom(y, (1. * h / y.shape[0], 1. * w / y.shape[1]), order=1, prefilter=False)
y = (np.arange(nb_classes) == y[:, :, None]).astype('float32')
assert y.shape[2] == nb_classes
images[i % batch_size] = img
labels[i % batch_size] = y
if (i + 1) % batch_size == 0:
yield images, labels
images, labels = update_inputs(batch_size=batch_size,
input_size=input_size, num_classes=nb_classes)
| [
"random.shuffle",
"numpy.zeros",
"os.path.exists",
"scipy.ndimage.zoom",
"collections.defaultdict",
"numpy.array",
"numpy.arange",
"os.path.join",
"os.listdir",
"cv2.resize"
] | [((134, 174), 'numpy.array', 'np.array', (['[[[123.68, 116.779, 103.939]]]'], {}), '([[[123.68, 116.779, 103.939]]])\n', (142, 174), True, 'import numpy as np\n'), ((225, 253), 'cv2.resize', 'cv2.resize', (['img', 'input_shape'], {}), '(img, input_shape)\n', (235, 253), False, 'import cv2\n'), ((814, 831), 'collections.defaultdict', 'defaultdict', (['dict'], {}), '(dict)\n', (825, 831), False, 'from collections import defaultdict\n'), ((848, 877), 'os.path.join', 'os.path.join', (['datadir', '"""imgs"""'], {}), "(datadir, 'imgs')\n", (860, 877), False, 'import os\n'), ((896, 917), 'os.listdir', 'os.listdir', (['image_dir'], {}), '(image_dir)\n', (906, 917), False, 'import os\n'), ((1053, 1091), 'os.path.join', 'os.path.join', (['datadir', '"""maps_bordered"""'], {}), "(datadir, 'maps_bordered')\n", (1065, 1091), False, 'import os\n'), ((1109, 1129), 'os.listdir', 'os.listdir', (['anno_dir'], {}), '(anno_dir)\n', (1119, 1129), False, 'import os\n'), ((1276, 1298), 'random.shuffle', 'random.shuffle', (['values'], {}), '(values)\n', (1290, 1298), False, 'import random\n'), ((431, 486), 'numpy.zeros', 'np.zeros', (['[batch_size, input_size[0], input_size[1], 3]'], {}), '([batch_size, input_size[0], input_size[1], 3])\n', (439, 486), True, 'import numpy as np\n'), ((501, 566), 'numpy.zeros', 'np.zeros', (['[batch_size, input_size[0], input_size[1], num_classes]'], {}), '([batch_size, input_size[0], input_size[1], num_classes])\n', (509, 566), True, 'import numpy as np\n'), ((695, 718), 'os.path.exists', 'os.path.exists', (['datadir'], {}), '(datadir)\n', (709, 718), False, 'import os\n'), ((1596, 1618), 'random.shuffle', 'random.shuffle', (['values'], {}), '(values)\n', (1610, 1618), False, 'import random\n'), ((1916, 1943), 'cv2.resize', 'cv2.resize', (['img', 'input_size'], {}), '(img, input_size)\n', (1926, 1943), False, 'import cv2\n'), ((2074, 2153), 'scipy.ndimage.zoom', 'zoom', (['y', '(1.0 * h / y.shape[0], 1.0 * w / y.shape[1])'], {'order': '(1)', 'prefilter': '(False)'}), '(y, (1.0 * h / y.shape[0], 1.0 * w / y.shape[1]), order=1, prefilter=False)\n', (2078, 2153), False, 'from scipy.ndimage import zoom\n'), ((1971, 2004), 'os.path.join', 'os.path.join', (['anno_dir', "d['anno']"], {}), "(anno_dir, d['anno'])\n", (1983, 2004), False, 'import os\n'), ((1835, 1870), 'os.path.join', 'os.path.join', (['image_dir', "d['image']"], {}), "(image_dir, d['image'])\n", (1847, 1870), False, 'import os\n'), ((2169, 2190), 'numpy.arange', 'np.arange', (['nb_classes'], {}), '(nb_classes)\n', (2178, 2190), True, 'import numpy as np\n')] |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import io
from numpy.testing import assert_approx_equal, assert_allclose, assert_array_equal
from nose.tools import assert_equal, assert_true, assert_false, assert_greater, assert_less
import cv2
import cv_algorithms
from cv_algorithms import Neighbours, Direction
import numpy as np
class TestNeighbours(object):
def test_binary_neighbours_simple(self):
"""Test binary direction detection"""
img = np.zeros((10,8), dtype=np.uint8)
y, x = 5, 4
img[5,4] = 255
# Currently just test whether it crashes
directions = cv_algorithms.binary_neighbours(img)
print(directions)
assert_equal(0, directions[0,0])
# NOTE: Directions are inversed, this is not a mistake
# To the pixel on the NW of the white pixel
# the white pixel is SE!
# Center
assert_equal(0, directions[5, 4])
# NW of the white pixel
assert_equal((y-1, x-1), Neighbours.northwest_coords(y, x))
assert_equal((y-1, x-1), Neighbours.coords(Direction.NorthWest, y, x))
assert_equal((1 << 7), directions[y-1, x-1])
assert_false(Neighbours.is_northwest(directions[y-1, x-1]))
assert_false(Neighbours.is_north(directions[y-1, x-1]))
assert_false(Neighbours.is_northeast(directions[y-1, x-1]))
assert_false(Neighbours.is_west(directions[y-1, x-1]))
assert_false(Neighbours.is_east(directions[y-1, x-1]))
assert_false(Neighbours.is_southwest(directions[y-1, x-1]))
assert_false(Neighbours.is_south(directions[y-1, x-1]))
assert_true(Neighbours.is_southeast(directions[y-1, x-1]))
# N of the white pixel
assert_equal((y-1, x), Neighbours.north_coords(y, x))
assert_equal((y-1, x), Neighbours.coords(Direction.North, y, x))
assert_equal((1 << 6), directions[y-1, x])
assert_false(Neighbours.is_northwest(directions[y-1, x]))
assert_false(Neighbours.is_north(directions[y-1, x]))
assert_false(Neighbours.is_northeast(directions[y-1, x]))
assert_false(Neighbours.is_west(directions[y-1, x]))
assert_false(Neighbours.is_east(directions[y-1, x]))
assert_false(Neighbours.is_southwest(directions[y-1, x]))
assert_true(Neighbours.is_south(directions[y-1, x]))
assert_false(Neighbours.is_southeast(directions[y-1, x]))
# NE of the white pixel
assert_equal((y-1, x+1), Neighbours.northeast_coords(y, x))
assert_equal((y-1, x+1), Neighbours.coords(Direction.NorthEast, y, x))
assert_equal((1 << 5), directions[y-1, x+1])
assert_false(Neighbours.is_northwest(directions[y-1, x+1]))
assert_false(Neighbours.is_north(directions[y-1, x+1]))
assert_false(Neighbours.is_northeast(directions[y-1, x+1]))
assert_false(Neighbours.is_west(directions[y-1, x+1]))
assert_false(Neighbours.is_east(directions[y-1, x+1]))
assert_true(Neighbours.is_southwest(directions[y-1, x+1]))
assert_false(Neighbours.is_south(directions[y-1, x+1]))
assert_false(Neighbours.is_southeast(directions[y-1, x+1]))
# W of the white pixel
assert_equal((y, x-1), Neighbours.west_coords(y, x))
assert_equal((y, x-1), Neighbours.coords(Direction.West, y, x))
assert_equal((1 << 4), directions[y, x-1])
assert_false(Neighbours.is_northwest(directions[y, x-1]))
assert_false(Neighbours.is_north(directions[y, x-1]))
assert_false(Neighbours.is_northeast(directions[y, x-1]))
assert_false(Neighbours.is_west(directions[y, x-1]))
assert_true(Neighbours.is_east(directions[y, x-1]))
assert_false(Neighbours.is_southwest(directions[y, x-1]))
assert_false(Neighbours.is_south(directions[y, x-1]))
assert_false(Neighbours.is_southeast(directions[y, x-1]))
# E of the white pixel
assert_equal((y, x+1), Neighbours.east_coords(y, x))
assert_equal((y, x+1), Neighbours.coords(Direction.East, y, x))
assert_equal((1 << 3), directions[y, x+1])
assert_false(Neighbours.is_northwest(directions[y, x+1]))
assert_false(Neighbours.is_north(directions[y, x+1]))
assert_false(Neighbours.is_northeast(directions[y, x+1]))
assert_true(Neighbours.is_west(directions[y, x+1]))
assert_false(Neighbours.is_east(directions[y, x+1]))
assert_false(Neighbours.is_southwest(directions[y, x+1]))
assert_false(Neighbours.is_south(directions[y, x+1]))
assert_false(Neighbours.is_southeast(directions[y, x+1]))
# SW of the white pixel
assert_equal((y+1, x-1), Neighbours.southwest_coords(y, x))
assert_equal((y+1, x-1), Neighbours.coords(Direction.SouthWest, y, x))
assert_equal((1 << 2), directions[y+1, x-1])
assert_false(Neighbours.is_northwest(directions[y+1, x-1]))
assert_false(Neighbours.is_north(directions[y+1, x-1]))
assert_true(Neighbours.is_northeast(directions[y+1, x-1]))
assert_false(Neighbours.is_west(directions[y+1, x-1]))
assert_false(Neighbours.is_east(directions[y+1, x-1]))
assert_false(Neighbours.is_southwest(directions[y+1, x-1]))
assert_false(Neighbours.is_south(directions[y+1, x-1]))
assert_false(Neighbours.is_southeast(directions[y+1, x-1]))
# S of the white pixel
assert_equal((y+1, x), Neighbours.south_coords(y, x))
assert_equal((y+1, x), Neighbours.coords(Direction.South, y, x))
assert_equal((1 << 1), directions[y+1, x])
assert_false(Neighbours.is_northwest(directions[y+1, x]))
assert_true(Neighbours.is_north(directions[y+1, x]))
assert_false(Neighbours.is_northeast(directions[y+1, x]))
assert_false(Neighbours.is_west(directions[y+1, x]))
assert_false(Neighbours.is_east(directions[y+1, x]))
assert_false(Neighbours.is_southwest(directions[y+1, x]))
assert_false(Neighbours.is_south(directions[y+1, x]))
assert_false(Neighbours.is_southeast(directions[y+1, x]))
# SE of the white pixel
assert_equal((y+1, x+1), Neighbours.southeast_coords(y, x))
assert_equal((y+1, x+1), Neighbours.coords(Direction.SouthEast, y, x))
assert_equal((1 << 0), directions[y+1, x+1])
assert_true(Neighbours.is_northwest(directions[y+1, x+1]))
assert_false(Neighbours.is_north(directions[y+1, x+1]))
assert_false(Neighbours.is_northeast(directions[y+1, x+1]))
assert_false(Neighbours.is_west(directions[y+1, x+1]))
assert_false(Neighbours.is_east(directions[y+1, x+1]))
assert_false(Neighbours.is_southwest(directions[y+1, x+1]))
assert_false(Neighbours.is_south(directions[y+1, x+1]))
assert_false(Neighbours.is_southeast(directions[y+1, x+1]))
def test_binary_neighbours_corner(self):
# Just test if it crashes for something in the corners
img = np.zeros((10,8), dtype=np.uint8)
img[9,7] = 255
img[0,0] = 255
cv_algorithms.binary_neighbours(img)
def test_direction_str(self):
assert_equal("↑", str(Direction.North))
assert_equal(Direction.North, Direction.from_unicode("↑"))
assert_equal([Direction.SouthEast, Direction.North], Direction.from_unicode("↘↑")) | [
"cv_algorithms.Neighbours.is_southeast",
"cv_algorithms.Neighbours.northwest_coords",
"cv_algorithms.Neighbours.is_south",
"cv_algorithms.Neighbours.is_northeast",
"cv_algorithms.Neighbours.west_coords",
"cv_algorithms.binary_neighbours",
"cv_algorithms.Neighbours.east_coords",
"cv_algorithms.Neighbou... | [((467, 500), 'numpy.zeros', 'np.zeros', (['(10, 8)'], {'dtype': 'np.uint8'}), '((10, 8), dtype=np.uint8)\n', (475, 500), True, 'import numpy as np\n'), ((613, 649), 'cv_algorithms.binary_neighbours', 'cv_algorithms.binary_neighbours', (['img'], {}), '(img)\n', (644, 649), False, 'import cv_algorithms\n'), ((684, 717), 'nose.tools.assert_equal', 'assert_equal', (['(0)', 'directions[0, 0]'], {}), '(0, directions[0, 0])\n', (696, 717), False, 'from nose.tools import assert_equal, assert_true, assert_false, assert_greater, assert_less\n'), ((891, 924), 'nose.tools.assert_equal', 'assert_equal', (['(0)', 'directions[5, 4]'], {}), '(0, directions[5, 4])\n', (903, 924), False, 'from nose.tools import assert_equal, assert_true, assert_false, assert_greater, assert_less\n'), ((1112, 1158), 'nose.tools.assert_equal', 'assert_equal', (['(1 << 7)', 'directions[y - 1, x - 1]'], {}), '(1 << 7, directions[y - 1, x - 1])\n', (1124, 1158), False, 'from nose.tools import assert_equal, assert_true, assert_false, assert_greater, assert_less\n'), ((1856, 1898), 'nose.tools.assert_equal', 'assert_equal', (['(1 << 6)', 'directions[y - 1, x]'], {}), '(1 << 6, directions[y - 1, x])\n', (1868, 1898), False, 'from nose.tools import assert_equal, assert_true, assert_false, assert_greater, assert_less\n'), ((2595, 2641), 'nose.tools.assert_equal', 'assert_equal', (['(1 << 5)', 'directions[y - 1, x + 1]'], {}), '(1 << 5, directions[y - 1, x + 1])\n', (2607, 2641), False, 'from nose.tools import assert_equal, assert_true, assert_false, assert_greater, assert_less\n'), ((3337, 3379), 'nose.tools.assert_equal', 'assert_equal', (['(1 << 4)', 'directions[y, x - 1]'], {}), '(1 << 4, directions[y, x - 1])\n', (3349, 3379), False, 'from nose.tools import assert_equal, assert_true, assert_false, assert_greater, assert_less\n'), ((4061, 4103), 'nose.tools.assert_equal', 'assert_equal', (['(1 << 3)', 'directions[y, x + 1]'], {}), '(1 << 3, directions[y, x + 1])\n', (4073, 4103), False, 'from nose.tools import assert_equal, assert_true, assert_false, assert_greater, assert_less\n'), ((4800, 4846), 'nose.tools.assert_equal', 'assert_equal', (['(1 << 2)', 'directions[y + 1, x - 1]'], {}), '(1 << 2, directions[y + 1, x - 1])\n', (4812, 4846), False, 'from nose.tools import assert_equal, assert_true, assert_false, assert_greater, assert_less\n'), ((5544, 5586), 'nose.tools.assert_equal', 'assert_equal', (['(1 << 1)', 'directions[y + 1, x]'], {}), '(1 << 1, directions[y + 1, x])\n', (5556, 5586), False, 'from nose.tools import assert_equal, assert_true, assert_false, assert_greater, assert_less\n'), ((6283, 6329), 'nose.tools.assert_equal', 'assert_equal', (['(1 << 0)', 'directions[y + 1, x + 1]'], {}), '(1 << 0, directions[y + 1, x + 1])\n', (6295, 6329), False, 'from nose.tools import assert_equal, assert_true, assert_false, assert_greater, assert_less\n'), ((6976, 7009), 'numpy.zeros', 'np.zeros', (['(10, 8)'], {'dtype': 'np.uint8'}), '((10, 8), dtype=np.uint8)\n', (6984, 7009), True, 'import numpy as np\n'), ((7063, 7099), 'cv_algorithms.binary_neighbours', 'cv_algorithms.binary_neighbours', (['img'], {}), '(img)\n', (7094, 7099), False, 'import cv_algorithms\n'), ((990, 1023), 'cv_algorithms.Neighbours.northwest_coords', 'Neighbours.northwest_coords', (['y', 'x'], {}), '(y, x)\n', (1017, 1023), False, 'from cv_algorithms import Neighbours, Direction\n'), ((1058, 1102), 'cv_algorithms.Neighbours.coords', 'Neighbours.coords', (['Direction.NorthWest', 'y', 'x'], {}), '(Direction.NorthWest, y, x)\n', (1075, 1102), False, 'from cv_algorithms import Neighbours, Direction\n'), ((1178, 1227), 'cv_algorithms.Neighbours.is_northwest', 'Neighbours.is_northwest', (['directions[y - 1, x - 1]'], {}), '(directions[y - 1, x - 1])\n', (1201, 1227), False, 'from cv_algorithms import Neighbours, Direction\n'), ((1246, 1291), 'cv_algorithms.Neighbours.is_north', 'Neighbours.is_north', (['directions[y - 1, x - 1]'], {}), '(directions[y - 1, x - 1])\n', (1265, 1291), False, 'from cv_algorithms import Neighbours, Direction\n'), ((1310, 1359), 'cv_algorithms.Neighbours.is_northeast', 'Neighbours.is_northeast', (['directions[y - 1, x - 1]'], {}), '(directions[y - 1, x - 1])\n', (1333, 1359), False, 'from cv_algorithms import Neighbours, Direction\n'), ((1378, 1422), 'cv_algorithms.Neighbours.is_west', 'Neighbours.is_west', (['directions[y - 1, x - 1]'], {}), '(directions[y - 1, x - 1])\n', (1396, 1422), False, 'from cv_algorithms import Neighbours, Direction\n'), ((1441, 1485), 'cv_algorithms.Neighbours.is_east', 'Neighbours.is_east', (['directions[y - 1, x - 1]'], {}), '(directions[y - 1, x - 1])\n', (1459, 1485), False, 'from cv_algorithms import Neighbours, Direction\n'), ((1504, 1553), 'cv_algorithms.Neighbours.is_southwest', 'Neighbours.is_southwest', (['directions[y - 1, x - 1]'], {}), '(directions[y - 1, x - 1])\n', (1527, 1553), False, 'from cv_algorithms import Neighbours, Direction\n'), ((1572, 1617), 'cv_algorithms.Neighbours.is_south', 'Neighbours.is_south', (['directions[y - 1, x - 1]'], {}), '(directions[y - 1, x - 1])\n', (1591, 1617), False, 'from cv_algorithms import Neighbours, Direction\n'), ((1635, 1684), 'cv_algorithms.Neighbours.is_southeast', 'Neighbours.is_southeast', (['directions[y - 1, x - 1]'], {}), '(directions[y - 1, x - 1])\n', (1658, 1684), False, 'from cv_algorithms import Neighbours, Direction\n'), ((1744, 1773), 'cv_algorithms.Neighbours.north_coords', 'Neighbours.north_coords', (['y', 'x'], {}), '(y, x)\n', (1767, 1773), False, 'from cv_algorithms import Neighbours, Direction\n'), ((1806, 1846), 'cv_algorithms.Neighbours.coords', 'Neighbours.coords', (['Direction.North', 'y', 'x'], {}), '(Direction.North, y, x)\n', (1823, 1846), False, 'from cv_algorithms import Neighbours, Direction\n'), ((1920, 1965), 'cv_algorithms.Neighbours.is_northwest', 'Neighbours.is_northwest', (['directions[y - 1, x]'], {}), '(directions[y - 1, x])\n', (1943, 1965), False, 'from cv_algorithms import Neighbours, Direction\n'), ((1986, 2027), 'cv_algorithms.Neighbours.is_north', 'Neighbours.is_north', (['directions[y - 1, x]'], {}), '(directions[y - 1, x])\n', (2005, 2027), False, 'from cv_algorithms import Neighbours, Direction\n'), ((2048, 2093), 'cv_algorithms.Neighbours.is_northeast', 'Neighbours.is_northeast', (['directions[y - 1, x]'], {}), '(directions[y - 1, x])\n', (2071, 2093), False, 'from cv_algorithms import Neighbours, Direction\n'), ((2114, 2154), 'cv_algorithms.Neighbours.is_west', 'Neighbours.is_west', (['directions[y - 1, x]'], {}), '(directions[y - 1, x])\n', (2132, 2154), False, 'from cv_algorithms import Neighbours, Direction\n'), ((2175, 2215), 'cv_algorithms.Neighbours.is_east', 'Neighbours.is_east', (['directions[y - 1, x]'], {}), '(directions[y - 1, x])\n', (2193, 2215), False, 'from cv_algorithms import Neighbours, Direction\n'), ((2236, 2281), 'cv_algorithms.Neighbours.is_southwest', 'Neighbours.is_southwest', (['directions[y - 1, x]'], {}), '(directions[y - 1, x])\n', (2259, 2281), False, 'from cv_algorithms import Neighbours, Direction\n'), ((2301, 2342), 'cv_algorithms.Neighbours.is_south', 'Neighbours.is_south', (['directions[y - 1, x]'], {}), '(directions[y - 1, x])\n', (2320, 2342), False, 'from cv_algorithms import Neighbours, Direction\n'), ((2363, 2408), 'cv_algorithms.Neighbours.is_southeast', 'Neighbours.is_southeast', (['directions[y - 1, x]'], {}), '(directions[y - 1, x])\n', (2386, 2408), False, 'from cv_algorithms import Neighbours, Direction\n'), ((2473, 2506), 'cv_algorithms.Neighbours.northeast_coords', 'Neighbours.northeast_coords', (['y', 'x'], {}), '(y, x)\n', (2500, 2506), False, 'from cv_algorithms import Neighbours, Direction\n'), ((2541, 2585), 'cv_algorithms.Neighbours.coords', 'Neighbours.coords', (['Direction.NorthEast', 'y', 'x'], {}), '(Direction.NorthEast, y, x)\n', (2558, 2585), False, 'from cv_algorithms import Neighbours, Direction\n'), ((2661, 2710), 'cv_algorithms.Neighbours.is_northwest', 'Neighbours.is_northwest', (['directions[y - 1, x + 1]'], {}), '(directions[y - 1, x + 1])\n', (2684, 2710), False, 'from cv_algorithms import Neighbours, Direction\n'), ((2729, 2774), 'cv_algorithms.Neighbours.is_north', 'Neighbours.is_north', (['directions[y - 1, x + 1]'], {}), '(directions[y - 1, x + 1])\n', (2748, 2774), False, 'from cv_algorithms import Neighbours, Direction\n'), ((2793, 2842), 'cv_algorithms.Neighbours.is_northeast', 'Neighbours.is_northeast', (['directions[y - 1, x + 1]'], {}), '(directions[y - 1, x + 1])\n', (2816, 2842), False, 'from cv_algorithms import Neighbours, Direction\n'), ((2861, 2905), 'cv_algorithms.Neighbours.is_west', 'Neighbours.is_west', (['directions[y - 1, x + 1]'], {}), '(directions[y - 1, x + 1])\n', (2879, 2905), False, 'from cv_algorithms import Neighbours, Direction\n'), ((2924, 2968), 'cv_algorithms.Neighbours.is_east', 'Neighbours.is_east', (['directions[y - 1, x + 1]'], {}), '(directions[y - 1, x + 1])\n', (2942, 2968), False, 'from cv_algorithms import Neighbours, Direction\n'), ((2986, 3035), 'cv_algorithms.Neighbours.is_southwest', 'Neighbours.is_southwest', (['directions[y - 1, x + 1]'], {}), '(directions[y - 1, x + 1])\n', (3009, 3035), False, 'from cv_algorithms import Neighbours, Direction\n'), ((3054, 3099), 'cv_algorithms.Neighbours.is_south', 'Neighbours.is_south', (['directions[y - 1, x + 1]'], {}), '(directions[y - 1, x + 1])\n', (3073, 3099), False, 'from cv_algorithms import Neighbours, Direction\n'), ((3118, 3167), 'cv_algorithms.Neighbours.is_southeast', 'Neighbours.is_southeast', (['directions[y - 1, x + 1]'], {}), '(directions[y - 1, x + 1])\n', (3141, 3167), False, 'from cv_algorithms import Neighbours, Direction\n'), ((3227, 3255), 'cv_algorithms.Neighbours.west_coords', 'Neighbours.west_coords', (['y', 'x'], {}), '(y, x)\n', (3249, 3255), False, 'from cv_algorithms import Neighbours, Direction\n'), ((3288, 3327), 'cv_algorithms.Neighbours.coords', 'Neighbours.coords', (['Direction.West', 'y', 'x'], {}), '(Direction.West, y, x)\n', (3305, 3327), False, 'from cv_algorithms import Neighbours, Direction\n'), ((3401, 3446), 'cv_algorithms.Neighbours.is_northwest', 'Neighbours.is_northwest', (['directions[y, x - 1]'], {}), '(directions[y, x - 1])\n', (3424, 3446), False, 'from cv_algorithms import Neighbours, Direction\n'), ((3467, 3508), 'cv_algorithms.Neighbours.is_north', 'Neighbours.is_north', (['directions[y, x - 1]'], {}), '(directions[y, x - 1])\n', (3486, 3508), False, 'from cv_algorithms import Neighbours, Direction\n'), ((3529, 3574), 'cv_algorithms.Neighbours.is_northeast', 'Neighbours.is_northeast', (['directions[y, x - 1]'], {}), '(directions[y, x - 1])\n', (3552, 3574), False, 'from cv_algorithms import Neighbours, Direction\n'), ((3595, 3635), 'cv_algorithms.Neighbours.is_west', 'Neighbours.is_west', (['directions[y, x - 1]'], {}), '(directions[y, x - 1])\n', (3613, 3635), False, 'from cv_algorithms import Neighbours, Direction\n'), ((3655, 3695), 'cv_algorithms.Neighbours.is_east', 'Neighbours.is_east', (['directions[y, x - 1]'], {}), '(directions[y, x - 1])\n', (3673, 3695), False, 'from cv_algorithms import Neighbours, Direction\n'), ((3716, 3761), 'cv_algorithms.Neighbours.is_southwest', 'Neighbours.is_southwest', (['directions[y, x - 1]'], {}), '(directions[y, x - 1])\n', (3739, 3761), False, 'from cv_algorithms import Neighbours, Direction\n'), ((3782, 3823), 'cv_algorithms.Neighbours.is_south', 'Neighbours.is_south', (['directions[y, x - 1]'], {}), '(directions[y, x - 1])\n', (3801, 3823), False, 'from cv_algorithms import Neighbours, Direction\n'), ((3844, 3889), 'cv_algorithms.Neighbours.is_southeast', 'Neighbours.is_southeast', (['directions[y, x - 1]'], {}), '(directions[y, x - 1])\n', (3867, 3889), False, 'from cv_algorithms import Neighbours, Direction\n'), ((3951, 3979), 'cv_algorithms.Neighbours.east_coords', 'Neighbours.east_coords', (['y', 'x'], {}), '(y, x)\n', (3973, 3979), False, 'from cv_algorithms import Neighbours, Direction\n'), ((4012, 4051), 'cv_algorithms.Neighbours.coords', 'Neighbours.coords', (['Direction.East', 'y', 'x'], {}), '(Direction.East, y, x)\n', (4029, 4051), False, 'from cv_algorithms import Neighbours, Direction\n'), ((4125, 4170), 'cv_algorithms.Neighbours.is_northwest', 'Neighbours.is_northwest', (['directions[y, x + 1]'], {}), '(directions[y, x + 1])\n', (4148, 4170), False, 'from cv_algorithms import Neighbours, Direction\n'), ((4191, 4232), 'cv_algorithms.Neighbours.is_north', 'Neighbours.is_north', (['directions[y, x + 1]'], {}), '(directions[y, x + 1])\n', (4210, 4232), False, 'from cv_algorithms import Neighbours, Direction\n'), ((4253, 4298), 'cv_algorithms.Neighbours.is_northeast', 'Neighbours.is_northeast', (['directions[y, x + 1]'], {}), '(directions[y, x + 1])\n', (4276, 4298), False, 'from cv_algorithms import Neighbours, Direction\n'), ((4318, 4358), 'cv_algorithms.Neighbours.is_west', 'Neighbours.is_west', (['directions[y, x + 1]'], {}), '(directions[y, x + 1])\n', (4336, 4358), False, 'from cv_algorithms import Neighbours, Direction\n'), ((4379, 4419), 'cv_algorithms.Neighbours.is_east', 'Neighbours.is_east', (['directions[y, x + 1]'], {}), '(directions[y, x + 1])\n', (4397, 4419), False, 'from cv_algorithms import Neighbours, Direction\n'), ((4440, 4485), 'cv_algorithms.Neighbours.is_southwest', 'Neighbours.is_southwest', (['directions[y, x + 1]'], {}), '(directions[y, x + 1])\n', (4463, 4485), False, 'from cv_algorithms import Neighbours, Direction\n'), ((4506, 4547), 'cv_algorithms.Neighbours.is_south', 'Neighbours.is_south', (['directions[y, x + 1]'], {}), '(directions[y, x + 1])\n', (4525, 4547), False, 'from cv_algorithms import Neighbours, Direction\n'), ((4568, 4613), 'cv_algorithms.Neighbours.is_southeast', 'Neighbours.is_southeast', (['directions[y, x + 1]'], {}), '(directions[y, x + 1])\n', (4591, 4613), False, 'from cv_algorithms import Neighbours, Direction\n'), ((4678, 4711), 'cv_algorithms.Neighbours.southwest_coords', 'Neighbours.southwest_coords', (['y', 'x'], {}), '(y, x)\n', (4705, 4711), False, 'from cv_algorithms import Neighbours, Direction\n'), ((4746, 4790), 'cv_algorithms.Neighbours.coords', 'Neighbours.coords', (['Direction.SouthWest', 'y', 'x'], {}), '(Direction.SouthWest, y, x)\n', (4763, 4790), False, 'from cv_algorithms import Neighbours, Direction\n'), ((4866, 4915), 'cv_algorithms.Neighbours.is_northwest', 'Neighbours.is_northwest', (['directions[y + 1, x - 1]'], {}), '(directions[y + 1, x - 1])\n', (4889, 4915), False, 'from cv_algorithms import Neighbours, Direction\n'), ((4934, 4979), 'cv_algorithms.Neighbours.is_north', 'Neighbours.is_north', (['directions[y + 1, x - 1]'], {}), '(directions[y + 1, x - 1])\n', (4953, 4979), False, 'from cv_algorithms import Neighbours, Direction\n'), ((4997, 5046), 'cv_algorithms.Neighbours.is_northeast', 'Neighbours.is_northeast', (['directions[y + 1, x - 1]'], {}), '(directions[y + 1, x - 1])\n', (5020, 5046), False, 'from cv_algorithms import Neighbours, Direction\n'), ((5065, 5109), 'cv_algorithms.Neighbours.is_west', 'Neighbours.is_west', (['directions[y + 1, x - 1]'], {}), '(directions[y + 1, x - 1])\n', (5083, 5109), False, 'from cv_algorithms import Neighbours, Direction\n'), ((5128, 5172), 'cv_algorithms.Neighbours.is_east', 'Neighbours.is_east', (['directions[y + 1, x - 1]'], {}), '(directions[y + 1, x - 1])\n', (5146, 5172), False, 'from cv_algorithms import Neighbours, Direction\n'), ((5191, 5240), 'cv_algorithms.Neighbours.is_southwest', 'Neighbours.is_southwest', (['directions[y + 1, x - 1]'], {}), '(directions[y + 1, x - 1])\n', (5214, 5240), False, 'from cv_algorithms import Neighbours, Direction\n'), ((5259, 5304), 'cv_algorithms.Neighbours.is_south', 'Neighbours.is_south', (['directions[y + 1, x - 1]'], {}), '(directions[y + 1, x - 1])\n', (5278, 5304), False, 'from cv_algorithms import Neighbours, Direction\n'), ((5323, 5372), 'cv_algorithms.Neighbours.is_southeast', 'Neighbours.is_southeast', (['directions[y + 1, x - 1]'], {}), '(directions[y + 1, x - 1])\n', (5346, 5372), False, 'from cv_algorithms import Neighbours, Direction\n'), ((5432, 5461), 'cv_algorithms.Neighbours.south_coords', 'Neighbours.south_coords', (['y', 'x'], {}), '(y, x)\n', (5455, 5461), False, 'from cv_algorithms import Neighbours, Direction\n'), ((5494, 5534), 'cv_algorithms.Neighbours.coords', 'Neighbours.coords', (['Direction.South', 'y', 'x'], {}), '(Direction.South, y, x)\n', (5511, 5534), False, 'from cv_algorithms import Neighbours, Direction\n'), ((5608, 5653), 'cv_algorithms.Neighbours.is_northwest', 'Neighbours.is_northwest', (['directions[y + 1, x]'], {}), '(directions[y + 1, x])\n', (5631, 5653), False, 'from cv_algorithms import Neighbours, Direction\n'), ((5673, 5714), 'cv_algorithms.Neighbours.is_north', 'Neighbours.is_north', (['directions[y + 1, x]'], {}), '(directions[y + 1, x])\n', (5692, 5714), False, 'from cv_algorithms import Neighbours, Direction\n'), ((5735, 5780), 'cv_algorithms.Neighbours.is_northeast', 'Neighbours.is_northeast', (['directions[y + 1, x]'], {}), '(directions[y + 1, x])\n', (5758, 5780), False, 'from cv_algorithms import Neighbours, Direction\n'), ((5801, 5841), 'cv_algorithms.Neighbours.is_west', 'Neighbours.is_west', (['directions[y + 1, x]'], {}), '(directions[y + 1, x])\n', (5819, 5841), False, 'from cv_algorithms import Neighbours, Direction\n'), ((5862, 5902), 'cv_algorithms.Neighbours.is_east', 'Neighbours.is_east', (['directions[y + 1, x]'], {}), '(directions[y + 1, x])\n', (5880, 5902), False, 'from cv_algorithms import Neighbours, Direction\n'), ((5923, 5968), 'cv_algorithms.Neighbours.is_southwest', 'Neighbours.is_southwest', (['directions[y + 1, x]'], {}), '(directions[y + 1, x])\n', (5946, 5968), False, 'from cv_algorithms import Neighbours, Direction\n'), ((5989, 6030), 'cv_algorithms.Neighbours.is_south', 'Neighbours.is_south', (['directions[y + 1, x]'], {}), '(directions[y + 1, x])\n', (6008, 6030), False, 'from cv_algorithms import Neighbours, Direction\n'), ((6051, 6096), 'cv_algorithms.Neighbours.is_southeast', 'Neighbours.is_southeast', (['directions[y + 1, x]'], {}), '(directions[y + 1, x])\n', (6074, 6096), False, 'from cv_algorithms import Neighbours, Direction\n'), ((6161, 6194), 'cv_algorithms.Neighbours.southeast_coords', 'Neighbours.southeast_coords', (['y', 'x'], {}), '(y, x)\n', (6188, 6194), False, 'from cv_algorithms import Neighbours, Direction\n'), ((6229, 6273), 'cv_algorithms.Neighbours.coords', 'Neighbours.coords', (['Direction.SouthEast', 'y', 'x'], {}), '(Direction.SouthEast, y, x)\n', (6246, 6273), False, 'from cv_algorithms import Neighbours, Direction\n'), ((6348, 6397), 'cv_algorithms.Neighbours.is_northwest', 'Neighbours.is_northwest', (['directions[y + 1, x + 1]'], {}), '(directions[y + 1, x + 1])\n', (6371, 6397), False, 'from cv_algorithms import Neighbours, Direction\n'), ((6416, 6461), 'cv_algorithms.Neighbours.is_north', 'Neighbours.is_north', (['directions[y + 1, x + 1]'], {}), '(directions[y + 1, x + 1])\n', (6435, 6461), False, 'from cv_algorithms import Neighbours, Direction\n'), ((6480, 6529), 'cv_algorithms.Neighbours.is_northeast', 'Neighbours.is_northeast', (['directions[y + 1, x + 1]'], {}), '(directions[y + 1, x + 1])\n', (6503, 6529), False, 'from cv_algorithms import Neighbours, Direction\n'), ((6548, 6592), 'cv_algorithms.Neighbours.is_west', 'Neighbours.is_west', (['directions[y + 1, x + 1]'], {}), '(directions[y + 1, x + 1])\n', (6566, 6592), False, 'from cv_algorithms import Neighbours, Direction\n'), ((6611, 6655), 'cv_algorithms.Neighbours.is_east', 'Neighbours.is_east', (['directions[y + 1, x + 1]'], {}), '(directions[y + 1, x + 1])\n', (6629, 6655), False, 'from cv_algorithms import Neighbours, Direction\n'), ((6674, 6723), 'cv_algorithms.Neighbours.is_southwest', 'Neighbours.is_southwest', (['directions[y + 1, x + 1]'], {}), '(directions[y + 1, x + 1])\n', (6697, 6723), False, 'from cv_algorithms import Neighbours, Direction\n'), ((6742, 6787), 'cv_algorithms.Neighbours.is_south', 'Neighbours.is_south', (['directions[y + 1, x + 1]'], {}), '(directions[y + 1, x + 1])\n', (6761, 6787), False, 'from cv_algorithms import Neighbours, Direction\n'), ((6806, 6855), 'cv_algorithms.Neighbours.is_southeast', 'Neighbours.is_southeast', (['directions[y + 1, x + 1]'], {}), '(directions[y + 1, x + 1])\n', (6829, 6855), False, 'from cv_algorithms import Neighbours, Direction\n'), ((7221, 7248), 'cv_algorithms.Direction.from_unicode', 'Direction.from_unicode', (['"""↑"""'], {}), "('↑')\n", (7243, 7248), False, 'from cv_algorithms import Neighbours, Direction\n'), ((7311, 7339), 'cv_algorithms.Direction.from_unicode', 'Direction.from_unicode', (['"""↘↑"""'], {}), "('↘↑')\n", (7333, 7339), False, 'from cv_algorithms import Neighbours, Direction\n')] |
import numpy as np
from stl import mesh
# Define the 8 vertices of the cube
# In total, 8 cubes must be defined, so this list will be expanded
# Symbols will subsitute for the numbers here. The symbols will pick
# numbers from the 4 dimensional points in the input cube.
# the input file to the program merely consists of the coordinates
# of each of the vertices in order [0,0,0,1], .. [1,1,1,1].
# to start with the 3d case will be symbolized.
vertices = np.array([\
[0, 0, 0], #0
[+1, 0, 0],#1
[+1, +1, 0], #2
[0, +1, 0], #3
[0, 0, +1],
[+1, 0, +1],
[+1, +1, +1],
[0, +1, +1]])
# Define the 12 triangles composing the cube
# This list can be made longer, so total size for 4-cube would be
# in lines of code, 12 * 8 since there are eight faces on a 4-cube.
faces = np.array([\
[0,3,1],
[1,3,2],
[0,4,7],
[0,7,3],
[4,5,6],
[4,6,7],
[5,1,2],
[5,2,6],
[2,3,6],
[3,7,6],
[0,1,5],
[0,5,4],])
# Create the mesh
cube = mesh.Mesh(np.zeros(faces.shape[0], dtype=mesh.Mesh.dtype))
for i, face in enumerate(faces):
print ("i = ", i)
for j in range(3):
print ("j =",j)
cube.vectors[i][j] = vertices[face[j],:]
print ("verices[face[j],:]",vertices[face[j],:2])
print ("cube.vectors",cube.vectors)
# Write the mesh to file "cube.stl"
print (cube)
cube.save('cube.stl')
| [
"numpy.zeros",
"numpy.array"
] | [((468, 583), 'numpy.array', 'np.array', (['[[0, 0, 0], [+1, 0, 0], [+1, +1, 0], [0, +1, 0], [0, 0, +1], [+1, 0, +1], [\n +1, +1, +1], [0, +1, +1]]'], {}), '([[0, 0, 0], [+1, 0, 0], [+1, +1, 0], [0, +1, 0], [0, 0, +1], [+1, \n 0, +1], [+1, +1, +1], [0, +1, +1]])\n', (476, 583), True, 'import numpy as np\n'), ((827, 973), 'numpy.array', 'np.array', (['[[0, 3, 1], [1, 3, 2], [0, 4, 7], [0, 7, 3], [4, 5, 6], [4, 6, 7], [5, 1, 2\n ], [5, 2, 6], [2, 3, 6], [3, 7, 6], [0, 1, 5], [0, 5, 4]]'], {}), '([[0, 3, 1], [1, 3, 2], [0, 4, 7], [0, 7, 3], [4, 5, 6], [4, 6, 7],\n [5, 1, 2], [5, 2, 6], [2, 3, 6], [3, 7, 6], [0, 1, 5], [0, 5, 4]])\n', (835, 973), True, 'import numpy as np\n'), ((1048, 1095), 'numpy.zeros', 'np.zeros', (['faces.shape[0]'], {'dtype': 'mesh.Mesh.dtype'}), '(faces.shape[0], dtype=mesh.Mesh.dtype)\n', (1056, 1095), True, 'import numpy as np\n')] |
import logging
import numpy as np
from pextant.lib.geoshapely import GeoPolygon
import pandas as pd
logger = logging.getLogger()
class TraversePath:
def __init__(self, geopolygon, z, x,y,em=None, derived=None):
self.geopolygon = geopolygon
self.z = z
self.x = x
self.y = y
self.em = em
self.derived = derived
@classmethod
def frommap(cls, geopolygon, em, sampling=1, derived=None):
coords = geopolygon.to(em.ROW_COL).T[::sampling].T
y, x = coords
z = em.dataset.get_datapoint(coords.transpose())
return cls(geopolygon, z, x, y, em, derived)
@classmethod
def fromnodes(cls, nodes):
em = nodes[0].mesh_element.parentMesh
states = np.array([node.state for node in nodes]).transpose()
derived = [node.derived for node in nodes]
derived_pd = pd.DataFrame.from_dict(derived[1:])
gp = GeoPolygon(em.ROW_COL, *states)
return cls.frommap(gp, em, derived_pd)
def xyz(self, ref=None):
if ref is None and self.em is not None:
ref = self.em.COL_ROW
if ref is not None:
return np.array((self.x, self.y, self.z))
else:
return [], [], []
def dr(self):
pass
class Explorer(object):
"""
This class is a model for an arbitrary explorer model
"""
def __init__(self, mass, parameters=None): # we initialize with mass only
# There used to be a gravity parameter, but it makes more sense to put it into EnvironmentalModel
self.type = "N/A" # type for each explorer
self.mass = mass
self.parameters = parameters # parameters object, used for shadowing
self.analytics = dict()
self.objectivefx = [
['Distance', self.distance, 'min'],
['Time', self.time, 'min'],
['Energy', self.energy_expenditure, 'min']
]
self.maxvelocity = 0.01 # a very small number non zero to prevent divide by infinity
self.minenergy ={}
def optimizevector(self, arg):
if isinstance(arg, str):
id = next((i for i, item in enumerate(self.objectivefx) if arg in item), None)
if id == None:
id = 2
# if the wrong syntax is passed in
vector = np.zeros(len(self.objectivefx))
vector[id] = 1
else:
vector = np.array(arg)
return vector
def distance(self, path_length):
return path_length
def velocity(self, slope):
pass # should return something that's purely a function of slope
def time(self, path_lengths, slopes):
v = self.velocity(slopes)
if (v == 0).any():
logger.debug("WARNING, divide by zero velocity")
return path_lengths / v
def energyRate(self, path_length, slope, g):
return 0 # this depends on velocity, time
def energy_expenditure(self, path_lengths, slopes, g):
return 0
class Astronaut(Explorer): # Astronaut extends Explorer
def __init__(self, mass, parameters=None):
super(Astronaut, self).__init__(mass, parameters)
self.type = 'Astronaut'
self.maxvelocity = 1.6 # the maximum velocity is 1.6 from Marquez 2008
self.minenergy = { # Aaron's thesis page 50
'Earth': lambda m: 1.504 * m + 53.298,
'Moon': lambda m: 2.295 * m + 52.936
}
def velocity(self, slopes):
if np.logical_or((slopes > 35), (slopes < -35)).any():
logger.debug("WARNING, there are some slopes steeper than 35 degrees")
# slope is in degrees, Marquez 2008
v = np.piecewise(slopes,
[slopes <= -20, (slopes > -20) & (slopes <= -10), (slopes > -10) & (slopes <= 0),
(slopes > 0) & (slopes <= 6), (slopes > 6) & (slopes <= 15), slopes > 15],
[0.05, lambda slope: 0.095 * slope + 1.95, lambda slope: 0.06 * slope + 1.6,
lambda slope: -0.2 * slope + 1.6, lambda slope: -0.039 * slope + 0.634, 0.05])
return v
def slope_energy_cost(self, path_lengths, slopes, g):
m = self.mass
downhill = slopes < 0
uphill = slopes >= 0
work_dz = m * g * path_lengths * np.sin(slopes)
energy_cost = np.empty(slopes.shape)
energy_cost[downhill] = 2.4 * work_dz[downhill] * 0.3 ** (abs(np.degrees(slopes[downhill])) / 7.65)
energy_cost[uphill] = 3.5 * work_dz[uphill]
return energy_cost
def level_energy_cost(self, path_lengths, slopes, v):
m = self.mass
w_level = (3.28 * m + 71.1) * (0.661 * np.cos(slopes) + 0.115 / v) * path_lengths
return w_level
def energy_expenditure(self, path_lengths, slopes_radians, g):
"""
Metabolic Rate Equations for a Suited Astronaut
From Santee, 2001
"""
v = self.velocity(np.degrees(slopes_radians))
slope_cost = self.slope_energy_cost(path_lengths, slopes_radians, g)
level_cost = self.level_energy_cost(path_lengths, slopes_radians, v)
total_cost = slope_cost + level_cost
return total_cost, v
def path_dl_slopes(self, path):
x, y, z = path.xyz()
res = path.em.resolution
xy = res * np.column_stack((x, y))
dxy = np.diff(xy, axis=0)
dl = np.sqrt(np.sum(np.square(dxy), axis=1))
dz = np.diff(z)
dr = np.sqrt(dl**2+dz**2)
slopes = np.arctan2(dz, dl)
return dl, slopes, dr
def path_time(self, path):
dl, slopes, _ = self.path_dl_slopes(path)
return self.time(dl, slopes)
def path_energy_expenditure(self, path, g=9.81):
dl, slopes, _ = self.path_dl_slopes(path)
return self.energy_expenditure(dl, slopes, g)
class FixedAstronaut(Astronaut):
def energy_expenditure(self, path_lengths, slopes_radians, g):
"""
Metabolic Rate Equations for a Suited Astronaut
From Santee, 2001
"""
path_lengths = path_lengths/np.cos(slopes_radians)
v = self.velocity(np.degrees(slopes_radians))
slope_cost = self.slope_energy_cost(path_lengths, slopes_radians, g)
level_cost = self.level_energy_cost(path_lengths, slopes_radians, v)
total_cost = slope_cost + level_cost
return total_cost, v
class Rover(Explorer): # Rover also extends explorer
def __init__(self, mass, parameters=None, constant_speed=15, additional_energy=1500):
Explorer.__init__(self, mass, parameters)
self.speed = constant_speed
self.P_e = additional_energy # The collection of all additional electronic components on the rover
# Modelled as a constant, estimated to be 1500 W
# In future iterations, perhaps we can change this to depend on the
# activities being performed during the exploration
self.type = 'Rover'
self.minenergy = {
'Earth': lambda m: 0.0, # rover on earth is not used
'Moon' : lambda m: 0.216 * m + self.P_e / 4.167
}
def velocity(self, slope=0):
return self.speed # we assume constant velocity for the rover
def energyRate(self, path_length, slope, g):
'''
Equations from Carr, 2001
Equations developed from historical data
Are all normalized to lunar gravity
'''
m = self.mass
v = self.velocity(slope)
P_e = self.P_e
w_level = 0.216 * m * v
if slope == 0:
w_slope = 0
elif slope > 0:
w_slope = 0.02628 * m * slope * (g / 1.62) * v
elif slope < 0:
w_slope = -0.007884 * m * slope * (g / 1.62) * v
return w_level + w_slope + P_e
class BASALTExplorer(Astronaut):
'''
Represents an explorer in the BASALT fields. Needs some data for the velocity function.
energyRate should be the same as the Astronaut.
'''
def __init__(self, mass, parameters=None):
super(Astronaut, self).__init__(mass, parameters)
self.type = 'BASALTExplorer'
def velocity(self, slope=0):
# Hopefully we can get this data after the first deployment
pass
class explorerParameters:
'''
NOTE: This will not be used at all for BASALT/MINERVA. It is
information that will be important for shadowing, which is likely
beyond the scope of the project.
This may eventually become incorporated into a different type of
energy cost function, especially for the rover. Currently the optimization
on energy only takes into account metabolic energy, and not energy
gained or lost from the sun and shadowing.
The explorer class should be designed such that this is optional
and only necessary if we wish to perform shadowing
The input p should be a dictionary of parameters
'''
def __init__(self, typeString, p=None):
if typeString == 'Astronaut' and p == None: # Default parameters for astronaut and rover
self.dConstraint = 0
self.tConstraint = 0
self.eConstraint = 0
self.shadowScaling = 120
self.emissivityMoon = 0.95
self.emissivitySuit = 0.837
self.absorptivitySuit = 0.18
self.solarConstant = 1367
self.TSpace = 3
self.VFSuitMoon = 0.5
self.VFSuitSpace = 0.5
self.height = 1.83
self.A_rad = 0.093
self.emissivityRad = 0
self.m_dot = 0.0302
self.cp_water = 4186
self.h_subWater = 2594000
self.conductivitySuit = 1.19
self.inletTemp = 288
self.TSuit_in = 300
self.mSuit = 50
self.cp_Suit = 1000
self.suitBatteryHeat = 50
elif typeString == 'Rover' and p == None:
self.efficiency_SA = 0.26
self.A_SA = 30
self.batterySpecificEnergy = 145
self.mBattery = 269
self.electronicsPower = 1400
elif typeString == 'Astronaut': # There should be a dictionary of parameters given
self.dConstraint = p['dConstraint']
self.tConstraint = p['tConstraint']
self.eConstraint = p['eConstraint']
self.shadowScaling = p['shadowScaling']
self.emissivityMoon = p['emissivityMoon']
self.emissivitySuit = p['emissivitySuit']
self.absorptivitySuit = p['absorptivitySuit']
self.solarConstant = p['solarConstant']
self.TSpace = p['TSpace']
self.VFSuitMoon = p['VFSuitMoon']
self.VFSuitSpace = p['VFSuitSpace']
self.height = p['height']
self.A_rad = p['A_rad']
self.emissivityRad = p['emissivityRad']
self.m_dot = p['m_dot']
self.cp_water = p['cp_water']
self.h_subWater = p['h_subwater']
self.conductivitySuit = p['conductivitySuit']
self.inletTemp = p['inletTemp']
self.TSuit_in = p['TSuit_in']
self.mSuit = p['mSuit']
self.cp_Suit = p['cp_Suit']
self.suitBatteryHeat = p['suitBatteryHeat']
elif typeString == 'Rover':
self.efficiency_SA = p['efficiency_SA']
self.A_SA = p['A_SA']
self.batterySpecificEnergy = p['batterySpecificEnergy']
self.mBattery = p['mBattery']
self.electronicsPower = p['electronicsPower']
if __name__ == '__main__':
import matplotlib.pyplot as plt
plt.rcParams['font.size'] = 14
slopes = np.linspace(-25, 25, 100)
a = Astronaut(80)
nrg = a.energyRate(np.ones_like(slopes), slopes, 9.81) / a.velocity(slopes)
plt.plot(slopes, nrg)
plt.xlabel('slope [degrees]')
plt.ylabel('Power [W]')
plt.title('Power output [Santee et al 2001], mass=80kg')
plt.show()
# print(min(nrg))
| [
"matplotlib.pyplot.title",
"numpy.arctan2",
"numpy.empty",
"numpy.sin",
"numpy.degrees",
"numpy.linspace",
"numpy.piecewise",
"matplotlib.pyplot.show",
"pandas.DataFrame.from_dict",
"numpy.ones_like",
"numpy.square",
"numpy.cos",
"pextant.lib.geoshapely.GeoPolygon",
"matplotlib.pyplot.ylab... | [((110, 129), 'logging.getLogger', 'logging.getLogger', ([], {}), '()\n', (127, 129), False, 'import logging\n'), ((11568, 11593), 'numpy.linspace', 'np.linspace', (['(-25)', '(25)', '(100)'], {}), '(-25, 25, 100)\n', (11579, 11593), True, 'import numpy as np\n'), ((11700, 11721), 'matplotlib.pyplot.plot', 'plt.plot', (['slopes', 'nrg'], {}), '(slopes, nrg)\n', (11708, 11721), True, 'import matplotlib.pyplot as plt\n'), ((11726, 11755), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""slope [degrees]"""'], {}), "('slope [degrees]')\n", (11736, 11755), True, 'import matplotlib.pyplot as plt\n'), ((11760, 11783), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Power [W]"""'], {}), "('Power [W]')\n", (11770, 11783), True, 'import matplotlib.pyplot as plt\n'), ((11788, 11844), 'matplotlib.pyplot.title', 'plt.title', (['"""Power output [Santee et al 2001], mass=80kg"""'], {}), "('Power output [Santee et al 2001], mass=80kg')\n", (11797, 11844), True, 'import matplotlib.pyplot as plt\n'), ((11849, 11859), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (11857, 11859), True, 'import matplotlib.pyplot as plt\n'), ((873, 908), 'pandas.DataFrame.from_dict', 'pd.DataFrame.from_dict', (['derived[1:]'], {}), '(derived[1:])\n', (895, 908), True, 'import pandas as pd\n'), ((922, 953), 'pextant.lib.geoshapely.GeoPolygon', 'GeoPolygon', (['em.ROW_COL', '*states'], {}), '(em.ROW_COL, *states)\n', (932, 953), False, 'from pextant.lib.geoshapely import GeoPolygon\n'), ((3673, 4025), 'numpy.piecewise', 'np.piecewise', (['slopes', '[slopes <= -20, (slopes > -20) & (slopes <= -10), (slopes > -10) & (slopes <=\n 0), (slopes > 0) & (slopes <= 6), (slopes > 6) & (slopes <= 15), slopes >\n 15]', '[0.05, lambda slope: 0.095 * slope + 1.95, lambda slope: 0.06 * slope + 1.6,\n lambda slope: -0.2 * slope + 1.6, lambda slope: -0.039 * slope + 0.634,\n 0.05]'], {}), '(slopes, [slopes <= -20, (slopes > -20) & (slopes <= -10), (\n slopes > -10) & (slopes <= 0), (slopes > 0) & (slopes <= 6), (slopes > \n 6) & (slopes <= 15), slopes > 15], [0.05, lambda slope: 0.095 * slope +\n 1.95, lambda slope: 0.06 * slope + 1.6, lambda slope: -0.2 * slope + \n 1.6, lambda slope: -0.039 * slope + 0.634, 0.05])\n', (3685, 4025), True, 'import numpy as np\n'), ((4344, 4366), 'numpy.empty', 'np.empty', (['slopes.shape'], {}), '(slopes.shape)\n', (4352, 4366), True, 'import numpy as np\n'), ((5361, 5380), 'numpy.diff', 'np.diff', (['xy'], {'axis': '(0)'}), '(xy, axis=0)\n', (5368, 5380), True, 'import numpy as np\n'), ((5447, 5457), 'numpy.diff', 'np.diff', (['z'], {}), '(z)\n', (5454, 5457), True, 'import numpy as np\n'), ((5471, 5497), 'numpy.sqrt', 'np.sqrt', (['(dl ** 2 + dz ** 2)'], {}), '(dl ** 2 + dz ** 2)\n', (5478, 5497), True, 'import numpy as np\n'), ((5509, 5527), 'numpy.arctan2', 'np.arctan2', (['dz', 'dl'], {}), '(dz, dl)\n', (5519, 5527), True, 'import numpy as np\n'), ((1161, 1195), 'numpy.array', 'np.array', (['(self.x, self.y, self.z)'], {}), '((self.x, self.y, self.z))\n', (1169, 1195), True, 'import numpy as np\n'), ((2417, 2430), 'numpy.array', 'np.array', (['arg'], {}), '(arg)\n', (2425, 2430), True, 'import numpy as np\n'), ((4307, 4321), 'numpy.sin', 'np.sin', (['slopes'], {}), '(slopes)\n', (4313, 4321), True, 'import numpy as np\n'), ((4949, 4975), 'numpy.degrees', 'np.degrees', (['slopes_radians'], {}), '(slopes_radians)\n', (4959, 4975), True, 'import numpy as np\n'), ((5323, 5346), 'numpy.column_stack', 'np.column_stack', (['(x, y)'], {}), '((x, y))\n', (5338, 5346), True, 'import numpy as np\n'), ((6079, 6101), 'numpy.cos', 'np.cos', (['slopes_radians'], {}), '(slopes_radians)\n', (6085, 6101), True, 'import numpy as np\n'), ((6128, 6154), 'numpy.degrees', 'np.degrees', (['slopes_radians'], {}), '(slopes_radians)\n', (6138, 6154), True, 'import numpy as np\n'), ((11639, 11659), 'numpy.ones_like', 'np.ones_like', (['slopes'], {}), '(slopes)\n', (11651, 11659), True, 'import numpy as np\n'), ((748, 788), 'numpy.array', 'np.array', (['[node.state for node in nodes]'], {}), '([node.state for node in nodes])\n', (756, 788), True, 'import numpy as np\n'), ((3481, 3521), 'numpy.logical_or', 'np.logical_or', (['(slopes > 35)', '(slopes < -35)'], {}), '(slopes > 35, slopes < -35)\n', (3494, 3521), True, 'import numpy as np\n'), ((5409, 5423), 'numpy.square', 'np.square', (['dxy'], {}), '(dxy)\n', (5418, 5423), True, 'import numpy as np\n'), ((4437, 4465), 'numpy.degrees', 'np.degrees', (['slopes[downhill]'], {}), '(slopes[downhill])\n', (4447, 4465), True, 'import numpy as np\n'), ((4683, 4697), 'numpy.cos', 'np.cos', (['slopes'], {}), '(slopes)\n', (4689, 4697), True, 'import numpy as np\n')] |
import numpy as np
__all__ = ['nd_pad', 'images_to_grid', 'grid_ground_truth']
def nd_pad(img: np.ndarray, pad_width: int, pad_value: float):
w, h, c = img.shape
w += 2 * pad_width
h += 2 * pad_width
padded_img = np.zeros((w, h, c), dtype='float32')
for i in range(c):
padded_img[..., i] = np.pad(img[..., i], pad_width=pad_width,
mode='constant', constant_values=pad_value)
return padded_img
def images_to_grid(images: np.ndarray, nrows: int, ncols: int, pad_width: int, pad_value: float = 35.0):
m, h, w, c = images.shape
if nrows * ncols != m:
raise ValueError(' nrows * ncols != No. images')
h += 2 * pad_width
w += 2 * pad_width
shape = (nrows * h, ncols * w, c)
grid_img = np.ones(shape, dtype='float32')
for i in range(nrows):
for j in range(ncols):
idx = i * ncols + j
s_h, e_h = i * h, (i + 1) * h
s_w, e_w = j * w, (j + 1) * w
pad_img = nd_pad(images[idx], pad_width, pad_value)
grid_img[s_h:e_h, s_w:e_w, :] = pad_img
return grid_img
def grid_ground_truth(grid_img: np.ndarray, images: np.ndarray, pad_width: int,
sep_width: int, pad_value_1: float = 35.0, pad_value_2: float = 1.0):
h, w, c = grid_img.shape
m, ih, iw, ic = images.shape
iw += 2 * pad_width
ih += 2 * pad_width
if m * ih != h or w % iw != 0:
raise ValueError('Inconsistent number of rows or cols, grid_img..., images=...')
if c != ic:
raise ValueError('number of channels must be the same,\
grid_img.shape[-1] != image.shape[-1]')
w += 2 * sep_width
shape = (h, w + iw, c)
new_grid_img = np.ones(shape, dtype='float32') + pad_value_2
gs_h, gs_w = 0, iw + (2 * sep_width)
new_grid_img[gs_h:, gs_w:] = grid_img
for i in range(m):
s_h, e_h = i * ih, (i + 1) * ih
pad_img = nd_pad(images[i], pad_width, pad_value_1)
new_grid_img[s_h:e_h, :iw, :] = pad_img
return new_grid_img
| [
"numpy.pad",
"numpy.zeros",
"numpy.ones"
] | [((235, 271), 'numpy.zeros', 'np.zeros', (['(w, h, c)'], {'dtype': '"""float32"""'}), "((w, h, c), dtype='float32')\n", (243, 271), True, 'import numpy as np\n'), ((794, 825), 'numpy.ones', 'np.ones', (['shape'], {'dtype': '"""float32"""'}), "(shape, dtype='float32')\n", (801, 825), True, 'import numpy as np\n'), ((326, 415), 'numpy.pad', 'np.pad', (['img[..., i]'], {'pad_width': 'pad_width', 'mode': '"""constant"""', 'constant_values': 'pad_value'}), "(img[..., i], pad_width=pad_width, mode='constant', constant_values=\n pad_value)\n", (332, 415), True, 'import numpy as np\n'), ((1771, 1802), 'numpy.ones', 'np.ones', (['shape'], {'dtype': '"""float32"""'}), "(shape, dtype='float32')\n", (1778, 1802), True, 'import numpy as np\n')] |
import random
from collections import Counter
import numpy as np
import sys
#from DTW import DTW
import FeatureExtract
from sklearn import neighbors
import MyEval
import dill
import pickle
import os.path
def read_expanded(fname):
'''
saved array should be read one by one,
change manually
example
write:
fout = open('../../data1/expanded_three_part_window_6000_stride_299.bin', 'wb')
np.save(fout, a1)
np.save(fout, a2)
fout.close()
print('save done')
read:
fin = open('../../data1/expanded_three_part_window_6000_stride_299.bin', 'rb')
a1 = np.load(fin)
a2 = np.load(fin)
fout.close()
'''
fin = open(fname, 'rb')
train_data_out = np.load(fin)
train_label_out = np.load(fin)
val_data_out = np.load(fin)
val_label_out = np.load(fin)
test_data_out = np.load(fin)
test_label_out = np.load(fin)
test_data_pid_out = np.load(fin)
fout.close()
return train_data_out, train_label_out, val_data_out, val_label_out, test_data_out, test_label_out, test_data_pid_out
def resample_unequal(ts, length):
resampled = [0.0] * length
resampled_idx = list(np.linspace(0.0, len(ts)-1, length))
for i in range(length):
idx_i = resampled_idx[i]
low_idx = int(np.floor(idx_i))
low_weight = abs(idx_i - np.ceil(idx_i))
high_idx = int(np.ceil(idx_i))
high_weight = abs(idx_i - np.floor(idx_i))
resampled[i] = low_weight * ts[low_idx] + high_weight * ts[high_idx]
# print(idx_i, resampled[i], low_weight, high_weight)
# break
return resampled
def read_centerwave(fin_name = '../../data1/centerwave_raw.csv'):
'''
data format:
[pid], [ts vector]\n
'''
my_pid = []
my_data = []
with open(fin_name) as fin:
for line in fin:
content = line.split(',')
pid = content[0]
data = [float(i) for i in content[1:]]
my_pid.append(pid)
my_data.append(data)
print("read_centerwave DONE, data shape: {0}".format(len(my_data)))
return my_data
def shrink_set_to_seq(pid_list, label):
'''
convert set of pids and labels to seq of pids and labels
labels are chars. ['N', 'A', 'O', '~']
now using vote, if same, choose last one
'''
label_char = ['N', 'A', 'O', '~']
out_label = []
label = np.array(label)
pid_list = np.array([ii.split('_')[0] for ii in pid_list])
pid_set = sorted(list(set([ii.split('_')[0] for ii in pid_list])))
for pid in pid_set:
tmp_label = label[pid_list == pid]
cnt = [0, 0, 0, 0]
for ii in tmp_label:
cnt[label_char.index(ii)] += 1
max_num = max(cnt)
if cnt[2] == max_num and cnt[1] == max_num and cnt[0] == max_num:
out_label.append('O')
elif cnt[2] == max_num and cnt[0] == max_num:
out_label.append('O')
elif cnt[1] == max_num and cnt[0] == max_num:
out_label.append('A')
elif cnt[2] == max_num and cnt[1] == max_num:
out_label.append('A')
else:
out_label.append(label_char[cnt.index(max_num)])
# print(tmp_label)
# print(Counter(tmp_label))
# print(out_label)
# break
return list(pid_set), out_label
def read_expanded(fname = '../../data1/expanded.pkl'):
with open(fname, 'rb') as fin:
out_data = pickle.load(fin)
out_label = pickle.load(fin)
return out_data, out_label
def DeleteNoiseData(pid, data, label):
"""
only retain 3 classes
"""
pass
def PreProcessData(data, label, max_seq_len):
"""
NOTICE:
We have to pad each sequence to reach 'max_seq_len' for TensorFlow
consistency (we cannot feed a numpy array with inconsistent
dimensions). The dynamic calculation will then be perform thanks to
'seqlen' attribute that records every actual sequence length.
"""
out_data = []
out_label = []
out_seqlen = []
my_len = len(data)
for i in range(my_len):
line = data[i]
if len(line) > max_seq_len:
out_data.append(line[:max_seq_len])
out_label.append(label[i])
out_seqlen.append(max_seq_len)
else:
append_ts = [0] *( max_seq_len - len(line))
out_data.append(line+append_ts)
out_label.append(label[i])
out_seqlen.append(len(line))
out_label = Label2OneHot(out_label)
out_data = np.array(out_data, dtype=np.float)
out_seqlen = np.array(out_seqlen, dtype=np.int64)
return out_data, out_label, out_seqlen
def GenValidation( fin_name, ratio, my_seed ):
"""
split patient ids into 2 groups, for offline validation
TODO: now using random to split, should use cross validation
"""
random.seed(my_seed)
all_pid = []
train_pid = []
val_pid = []
fin = open(fin_name)
for line in fin.readlines():
content = line.split(',')
pid = content[0]
all_pid.append(pid)
rnd = random.uniform(0.0, 1.0)
if rnd > ratio:
train_pid.append(pid)
else:
val_pid.append(pid)
fin.close()
print('GenValidation DONE')
return all_pid, train_pid, val_pid
def SplitDataByPid(pid, data, label, train_pid, val_pid):
'''
split data based on pid
pid should have same rows with data
'''
my_train_data = []
my_train_label = []
my_val_data = []
my_val_label = []
my_len = len(pid)
for i in range(my_len):
tmp_pid = pid[i]
tmp_data = data[i]
tmp_label = label[i]
if tmp_pid in train_pid:
my_train_data.append(tmp_data)
my_train_label.append(tmp_label)
else:
my_val_data.append(tmp_data)
my_val_label.append(tmp_label)
print("SplitDataByPid DONE")
return my_train_data, my_train_label, my_val_data, my_val_label
def SplitDataByPid1(pid, data, label, train_pid, val_pid):
'''
split data based on pid
also return pid
pid should have same rows with data
'''
my_train_data = []
my_train_label = []
my_train_pid = []
my_val_data = []
my_val_label = []
my_val_pid = []
my_len = len(pid)
for i in range(my_len):
tmp_pid = pid[i]
tmp_data = data[i]
tmp_label = label[i]
if tmp_pid in train_pid:
my_train_data.append(tmp_data)
my_train_label.append(tmp_label)
my_train_pid.append(tmp_pid)
else:
my_val_data.append(tmp_data)
my_val_label.append(tmp_label)
my_val_pid.append(tmp_pid)
print("SplitDataByPid DONE")
return my_train_data, my_train_label, my_train_pid, my_val_data, my_val_label, my_val_pid
def ReadData( fin_name):
'''
data format:
[pid], [label], [ts vector]\n
'''
my_pid = []
my_data = []
my_label = []
c = 0
co =0
cn = 0
with open(fin_name) as fin:
for line in fin:
content = line.strip().split(',')
pid = content[0]
label = content[1]
# data = [float(i) for i in content[2:]]
try:
data = [float(i) for i in content[2:]]
except:
print(line)
break
# if label == 'A' or label == '~':
# continue
# if label == 'N':
# c += 1
# if c > 2456:
# continue
# cn += 1
# if label == 'O':
# co +=1
my_pid.append(pid)
my_data.append(data)
my_label.append(label)
# print(my_data)
# break
print("Read data DONE")
print(len(my_data))
# print (co)
# print (cn)
return my_pid, my_data, my_label
def ReadSmall():
"""
read a small dataset for quick test
2 classes
"""
all_pid, train_pid, val_pid = GenValidation( '../../REFERENCE.csv', 0.2, 1 )
QRS_pid, QRS_data, QRS_label = ReadData( '../../data1/QRSinfo.csv' )
train_QRS_data, train_QRS_label, val_QRS_data, val_QRS_label = SplitDataByPid(QRS_pid, QRS_data, QRS_label, train_pid, val_pid)
QRS_train_feature = FeatureExtract.GetQRSFeature(train_QRS_data)
QRS_val_feature = FeatureExtract.GetQRSFeature(val_QRS_data)
for ii in range(len(train_QRS_label)):
if train_QRS_label[ii] != '~':
train_QRS_label[ii] = 'X'
for ii in range(len(val_QRS_label)):
if val_QRS_label[ii] != '~':
val_QRS_label[ii] = 'X'
return np.array(QRS_train_feature), train_QRS_label, np.array(QRS_val_feature), val_QRS_label
def ReadTestData( fin_name ):
'''
Read data without ID and label
data format:
[pid], [label], [ts vector]\n
'''
with open(fin_name) as fin:
for line in fin:
content = line.split(',')
data = [float(i) for i in content]
print("Read data DONE")
return data
def Label2OneHot(labels):
# label_enum = ['N', 'O']#, 'A', '~']
label_enum = ['N', 'A', 'O', '~']
my_len = len(labels)
out = np.zeros([my_len, len(label_enum)])
for i in range(my_len):
label = labels[i]
out[i, label_enum.index(label)] = 1.0
return out
def OneHot2Label(out):
label_enum = ['N', 'A', 'O', '~']
labels = []
my_len = out.shape[0]
for ii in range(my_len):
idx = list(out[ii,:]).index(1)
labels.append(label_enum[idx])
return labels
def Index2Label(out):
label_enum = ['N', 'A', 'O', '~']
labels = []
for ii in out:
labels.append(label_enum[ii])
return labels
def Label2Index(out):
label_enum = ['N', 'A', 'O', '~']
labels = []
for ii in out:
labels.append(label_enum.index(ii))
return labels
def LabelTo2(labels, pos_label):
out = []
for label in labels:
if label == pos_label:
out.append(1)
else:
out.append(0)
return out
def ProcessDataForNA(data, label):
out_data = []
out_label = []
for i in range(len(label)):
if label[i] == 'N':
out_data.append(data[i])
out_label.append(0)
elif label[i] == 'A':
out_data.append(data[i])
out_label.append(1)
return out_data, out_label
def ProcessDataForNoise(data, label):
out_data = []
out_label = []
for i in range(len(label)):
if label[i] == '~':
out_data.append(data[i])
out_label.append(1)
else:
out_data.append(data[i])
out_label.append(0)
return out_data, out_label
def TestFeatureQuality():
'''
test if nan inf in features
'''
with open('../../data2/features_all_v1.3.pkl', 'rb') as my_input:
all_pid = dill.load(my_input)
all_feature = dill.load(my_input)
all_label = dill.load(my_input)
all_feature = np.array(all_feature)
print('nan: ', sum(sum(np.isnan(all_feature))))
print('isposinf: ', sum(sum(np.isposinf(all_feature))))
print('isneginf: ', sum(sum(np.isneginf(all_feature))))
return
if __name__ == '__main__':
shrink_set_to_seq(test_pid, test_label)
| [
"numpy.load",
"numpy.ceil",
"FeatureExtract.GetQRSFeature",
"random.uniform",
"numpy.floor",
"numpy.isneginf",
"dill.load",
"numpy.isnan",
"pickle.load",
"numpy.array",
"random.seed",
"numpy.isposinf"
] | [((764, 776), 'numpy.load', 'np.load', (['fin'], {}), '(fin)\n', (771, 776), True, 'import numpy as np\n'), ((799, 811), 'numpy.load', 'np.load', (['fin'], {}), '(fin)\n', (806, 811), True, 'import numpy as np\n'), ((831, 843), 'numpy.load', 'np.load', (['fin'], {}), '(fin)\n', (838, 843), True, 'import numpy as np\n'), ((864, 876), 'numpy.load', 'np.load', (['fin'], {}), '(fin)\n', (871, 876), True, 'import numpy as np\n'), ((897, 909), 'numpy.load', 'np.load', (['fin'], {}), '(fin)\n', (904, 909), True, 'import numpy as np\n'), ((931, 943), 'numpy.load', 'np.load', (['fin'], {}), '(fin)\n', (938, 943), True, 'import numpy as np\n'), ((968, 980), 'numpy.load', 'np.load', (['fin'], {}), '(fin)\n', (975, 980), True, 'import numpy as np\n'), ((2479, 2494), 'numpy.array', 'np.array', (['label'], {}), '(label)\n', (2487, 2494), True, 'import numpy as np\n'), ((4624, 4658), 'numpy.array', 'np.array', (['out_data'], {'dtype': 'np.float'}), '(out_data, dtype=np.float)\n', (4632, 4658), True, 'import numpy as np\n'), ((4676, 4712), 'numpy.array', 'np.array', (['out_seqlen'], {'dtype': 'np.int64'}), '(out_seqlen, dtype=np.int64)\n', (4684, 4712), True, 'import numpy as np\n'), ((4964, 4984), 'random.seed', 'random.seed', (['my_seed'], {}), '(my_seed)\n', (4975, 4984), False, 'import random\n'), ((8566, 8610), 'FeatureExtract.GetQRSFeature', 'FeatureExtract.GetQRSFeature', (['train_QRS_data'], {}), '(train_QRS_data)\n', (8594, 8610), False, 'import FeatureExtract\n'), ((8633, 8675), 'FeatureExtract.GetQRSFeature', 'FeatureExtract.GetQRSFeature', (['val_QRS_data'], {}), '(val_QRS_data)\n', (8661, 8675), False, 'import FeatureExtract\n'), ((11404, 11425), 'numpy.array', 'np.array', (['all_feature'], {}), '(all_feature)\n', (11412, 11425), True, 'import numpy as np\n'), ((3530, 3546), 'pickle.load', 'pickle.load', (['fin'], {}), '(fin)\n', (3541, 3546), False, 'import pickle\n'), ((3567, 3583), 'pickle.load', 'pickle.load', (['fin'], {}), '(fin)\n', (3578, 3583), False, 'import pickle\n'), ((5203, 5227), 'random.uniform', 'random.uniform', (['(0.0)', '(1.0)'], {}), '(0.0, 1.0)\n', (5217, 5227), False, 'import random\n'), ((8921, 8948), 'numpy.array', 'np.array', (['QRS_train_feature'], {}), '(QRS_train_feature)\n', (8929, 8948), True, 'import numpy as np\n'), ((8967, 8992), 'numpy.array', 'np.array', (['QRS_val_feature'], {}), '(QRS_val_feature)\n', (8975, 8992), True, 'import numpy as np\n'), ((11275, 11294), 'dill.load', 'dill.load', (['my_input'], {}), '(my_input)\n', (11284, 11294), False, 'import dill\n'), ((11317, 11336), 'dill.load', 'dill.load', (['my_input'], {}), '(my_input)\n', (11326, 11336), False, 'import dill\n'), ((11357, 11376), 'dill.load', 'dill.load', (['my_input'], {}), '(my_input)\n', (11366, 11376), False, 'import dill\n'), ((1345, 1360), 'numpy.floor', 'np.floor', (['idx_i'], {}), '(idx_i)\n', (1353, 1360), True, 'import numpy as np\n'), ((1434, 1448), 'numpy.ceil', 'np.ceil', (['idx_i'], {}), '(idx_i)\n', (1441, 1448), True, 'import numpy as np\n'), ((1395, 1409), 'numpy.ceil', 'np.ceil', (['idx_i'], {}), '(idx_i)\n', (1402, 1409), True, 'import numpy as np\n'), ((1484, 1499), 'numpy.floor', 'np.floor', (['idx_i'], {}), '(idx_i)\n', (1492, 1499), True, 'import numpy as np\n'), ((11453, 11474), 'numpy.isnan', 'np.isnan', (['all_feature'], {}), '(all_feature)\n', (11461, 11474), True, 'import numpy as np\n'), ((11510, 11534), 'numpy.isposinf', 'np.isposinf', (['all_feature'], {}), '(all_feature)\n', (11521, 11534), True, 'import numpy as np\n'), ((11570, 11594), 'numpy.isneginf', 'np.isneginf', (['all_feature'], {}), '(all_feature)\n', (11581, 11594), True, 'import numpy as np\n')] |
from models.yolov3.constants import PathConstants
from tensorflow.keras.models import load_model
from utils.non_max_suppression import classic_non_max_suppression
import time
import tensorflow.keras.backend as K
import numpy as np
import tensorflow as tf
from typing import Tuple
NUM_OF_CLASSES = 601
NUM_OF_BOX_PARAMS = 5
NUM_OF_ANCHORS = 3
def restore_model(path_to_model = PathConstants.YOLOV3_MODEL_OPENIMAGES_OUT_PATH):
return load_model(path_to_model)
def construct_grid(rows, cols):
grid_x = K.arange(0, stop=cols)
grid_x = K.reshape(grid_x, [1, -1, 1, 1])
grid_x = K.tile(grid_x, [rows, 1, 1, 1])
grid_y = K.arange(0, stop=rows)
grid_y = K.reshape(grid_y, [-1, 1, 1, 1])
grid_y = K.tile(grid_y, [1, cols, 1, 1])
grid = K.concatenate([grid_x, grid_y])
return grid
def _infer_network_outputs(
*,
sess,
restored_model,
num_of_anchors,
anchors,
orig_image_width,
orig_image_height,
model_image_width,
model_image_height,
img_np,
verbose
):
start = time.time()
boxes = []
prob_class = []
for yolo_head_idx in range(len(restored_model.output)):
yolo_head = restored_model.output[yolo_head_idx]
yolo_head_shape = K.shape(yolo_head)
yolo_head_num_of_cols, yolo_head_num_of_rows = yolo_head_shape[2], yolo_head_shape[1]
curr_yolo_head = K.reshape(yolo_head, [-1, yolo_head_num_of_cols, yolo_head_num_of_rows, num_of_anchors,
NUM_OF_BOX_PARAMS + NUM_OF_CLASSES])
grid = construct_grid(yolo_head_shape[1], yolo_head_shape[2])
grid = K.cast(grid, dtype=K.dtype(curr_yolo_head))
grid_size = K.cast([yolo_head_num_of_cols, yolo_head_num_of_rows], dtype=K.dtype(curr_yolo_head))
curr_boxes_xy = (K.sigmoid(curr_yolo_head[..., :2]) + grid) / grid_size
curr_boxes_wh = K.exp(curr_yolo_head[..., 2:4]) * anchors[yolo_head_idx]
curr_prob_obj = K.sigmoid(curr_yolo_head[..., 4:5])
curr_prob_class = K.sigmoid(curr_yolo_head[..., 5:])
curr_prob_detected_class = curr_prob_obj * curr_prob_class
boxes.append(get_corrected_boxes(
box_width=curr_boxes_wh[..., 0:1],
box_height=curr_boxes_wh[..., 1:2],
box_x=curr_boxes_xy[..., 0:1],
box_y=curr_boxes_xy[..., 1:2],
orig_image_shape=(orig_image_width, orig_image_height),
model_image_shape=(model_image_width, model_image_height)
))
curr_prob_detected_class = K.reshape(curr_prob_detected_class, [-1, NUM_OF_CLASSES])
prob_class.append(curr_prob_detected_class)
prob_class = K.concatenate(prob_class, axis=0)
boxes = K.concatenate(boxes, axis=0)
out_tensors = [
boxes,
prob_class,
]
if verbose:
print(f'Took {time.time() - start} seconds to construct network.')
start = time.time()
sess_out = sess.run(out_tensors, feed_dict={
restored_model.input: img_np,
K.learning_phase(): 0
})
if verbose:
print(f'Took {time.time() - start} seconds to infer outputs in session.')
boxes, out_boxes_classes = sess_out
return boxes, out_boxes_classes
def infer_objects_in_image(
*,
image: np.array,
session: tf.Session,
orig_image_height: int,
orig_image_width: int,
detection_prob_treshold=0.5,
nms_threshold=0.6,
model_image_height: int,
model_image_width: int,
anchors: np.array,
restored_model: tf.keras.Model,
num_of_anchors: int = NUM_OF_ANCHORS,
num_of_classes=NUM_OF_CLASSES
):
boxes, classes_probs = _infer_network_outputs(
sess=session,
model_image_height=model_image_height,
model_image_width=model_image_width,
anchors=anchors,
img_np=image,
orig_image_width=orig_image_width,
orig_image_height=orig_image_height,
restored_model=restored_model,
num_of_anchors=num_of_anchors
)
all_curr_detected_objects = []
all_curr_detected_classes = []
all_curr_detected_scores = []
for c in range(num_of_classes):
curr_mask_detected = classes_probs[..., c] > detection_prob_treshold
curr_probs_class = classes_probs[curr_mask_detected, :][:, c]
c_boxes = boxes[curr_mask_detected, :]
curr_detected_objects = []
curr_detected_classes = []
curr_detected_scores = []
for idx in range(np.count_nonzero(curr_mask_detected)):
box_class_prob = curr_probs_class[idx]
curr_detected_objects += [c_boxes[idx]]
curr_detected_classes += [c]
curr_detected_scores += [box_class_prob]
if len(curr_detected_objects) > 0:
chosen_box_indices = classic_non_max_suppression(curr_detected_objects, curr_detected_scores, nms_threshold)
curr_detected_objects = [curr_detected_objects[i] for i in chosen_box_indices]
curr_detected_classes = [curr_detected_classes[i] for i in chosen_box_indices]
curr_detected_scores = [curr_detected_scores[i] for i in chosen_box_indices]
all_curr_detected_objects += curr_detected_objects
all_curr_detected_classes += curr_detected_classes
all_curr_detected_scores += curr_detected_scores
return all_curr_detected_objects, all_curr_detected_classes, all_curr_detected_scores
def get_corrected_boxes(
*,
box_width: tf.Tensor,
box_height: tf.Tensor,
box_x: tf.Tensor,
box_y: tf.Tensor,
orig_image_shape: Tuple[tf.Tensor],
model_image_shape: Tuple[float]
):
"""
Post-process outputs produced by YOLOv3 CNN network.
We letter-box and resize image into fixed size.
The function transforms predictions into original dimensions of the image.
:param box_width: predicted box widths by YOLOv3
:param box_height: predicted box heights by YOLOv3
:param box_x: predicted x coordinates of the center of the box
:param box_y: predicted y coordinates of the center of the box
:param orig_image_shape: (width, height) of original image
:param model_image_shape: (width, height) of resized image used as input to the model
:return: corrected boxes to match original dimensions of image
"""
orig_image_w, orig_image_h = orig_image_shape[0], orig_image_shape[1]
model_w, model_h = model_image_shape[0], model_image_shape[1]
if float(model_w / orig_image_w) < float(model_h / orig_image_h):
w_without_padding = model_w
h_without_padding = (orig_image_h) * model_w / orig_image_w
else:
h_without_padding = model_h
w_without_padding = (orig_image_w) * model_h / orig_image_h
x_shift = (model_w - w_without_padding) / 2.0 / model_w
y_shift = (model_h - h_without_padding) / 2.0 / model_h
box_x = (box_x - x_shift) / (w_without_padding / model_w)
box_y = (box_y - y_shift) / (h_without_padding / model_h)
box_width *= model_w / w_without_padding
box_height *= model_h / h_without_padding
left = (box_x - (box_width / 2.)) * orig_image_w
right = (box_x + (box_width / 2.)) * orig_image_w
top = (box_y - (box_height / 2.)) * orig_image_h
bottom = (box_y + (box_height / 2.)) * orig_image_h
output_boxes = K.concatenate([
K.reshape(left, [-1, 1]),
K.reshape(top, [-1, 1]),
K.reshape(right, [-1, 1]),
K.reshape(bottom, [-1, 1])
])
return output_boxes
| [
"tensorflow.keras.backend.arange",
"tensorflow.keras.models.load_model",
"tensorflow.keras.backend.sigmoid",
"numpy.count_nonzero",
"tensorflow.keras.backend.dtype",
"tensorflow.keras.backend.tile",
"tensorflow.keras.backend.reshape",
"tensorflow.keras.backend.shape",
"tensorflow.keras.backend.learn... | [((440, 465), 'tensorflow.keras.models.load_model', 'load_model', (['path_to_model'], {}), '(path_to_model)\n', (450, 465), False, 'from tensorflow.keras.models import load_model\n'), ((512, 534), 'tensorflow.keras.backend.arange', 'K.arange', (['(0)'], {'stop': 'cols'}), '(0, stop=cols)\n', (520, 534), True, 'import tensorflow.keras.backend as K\n'), ((548, 580), 'tensorflow.keras.backend.reshape', 'K.reshape', (['grid_x', '[1, -1, 1, 1]'], {}), '(grid_x, [1, -1, 1, 1])\n', (557, 580), True, 'import tensorflow.keras.backend as K\n'), ((594, 625), 'tensorflow.keras.backend.tile', 'K.tile', (['grid_x', '[rows, 1, 1, 1]'], {}), '(grid_x, [rows, 1, 1, 1])\n', (600, 625), True, 'import tensorflow.keras.backend as K\n'), ((640, 662), 'tensorflow.keras.backend.arange', 'K.arange', (['(0)'], {'stop': 'rows'}), '(0, stop=rows)\n', (648, 662), True, 'import tensorflow.keras.backend as K\n'), ((676, 708), 'tensorflow.keras.backend.reshape', 'K.reshape', (['grid_y', '[-1, 1, 1, 1]'], {}), '(grid_y, [-1, 1, 1, 1])\n', (685, 708), True, 'import tensorflow.keras.backend as K\n'), ((722, 753), 'tensorflow.keras.backend.tile', 'K.tile', (['grid_y', '[1, cols, 1, 1]'], {}), '(grid_y, [1, cols, 1, 1])\n', (728, 753), True, 'import tensorflow.keras.backend as K\n'), ((766, 797), 'tensorflow.keras.backend.concatenate', 'K.concatenate', (['[grid_x, grid_y]'], {}), '([grid_x, grid_y])\n', (779, 797), True, 'import tensorflow.keras.backend as K\n'), ((1046, 1057), 'time.time', 'time.time', ([], {}), '()\n', (1055, 1057), False, 'import time\n'), ((2673, 2706), 'tensorflow.keras.backend.concatenate', 'K.concatenate', (['prob_class'], {'axis': '(0)'}), '(prob_class, axis=0)\n', (2686, 2706), True, 'import tensorflow.keras.backend as K\n'), ((2719, 2747), 'tensorflow.keras.backend.concatenate', 'K.concatenate', (['boxes'], {'axis': '(0)'}), '(boxes, axis=0)\n', (2732, 2747), True, 'import tensorflow.keras.backend as K\n'), ((2915, 2926), 'time.time', 'time.time', ([], {}), '()\n', (2924, 2926), False, 'import time\n'), ((1237, 1255), 'tensorflow.keras.backend.shape', 'K.shape', (['yolo_head'], {}), '(yolo_head)\n', (1244, 1255), True, 'import tensorflow.keras.backend as K\n'), ((1376, 1504), 'tensorflow.keras.backend.reshape', 'K.reshape', (['yolo_head', '[-1, yolo_head_num_of_cols, yolo_head_num_of_rows, num_of_anchors, \n NUM_OF_BOX_PARAMS + NUM_OF_CLASSES]'], {}), '(yolo_head, [-1, yolo_head_num_of_cols, yolo_head_num_of_rows,\n num_of_anchors, NUM_OF_BOX_PARAMS + NUM_OF_CLASSES])\n', (1385, 1504), True, 'import tensorflow.keras.backend as K\n'), ((1972, 2007), 'tensorflow.keras.backend.sigmoid', 'K.sigmoid', (['curr_yolo_head[..., 4:5]'], {}), '(curr_yolo_head[..., 4:5])\n', (1981, 2007), True, 'import tensorflow.keras.backend as K\n'), ((2034, 2068), 'tensorflow.keras.backend.sigmoid', 'K.sigmoid', (['curr_yolo_head[..., 5:]'], {}), '(curr_yolo_head[..., 5:])\n', (2043, 2068), True, 'import tensorflow.keras.backend as K\n'), ((2545, 2602), 'tensorflow.keras.backend.reshape', 'K.reshape', (['curr_prob_detected_class', '[-1, NUM_OF_CLASSES]'], {}), '(curr_prob_detected_class, [-1, NUM_OF_CLASSES])\n', (2554, 2602), True, 'import tensorflow.keras.backend as K\n'), ((1890, 1921), 'tensorflow.keras.backend.exp', 'K.exp', (['curr_yolo_head[..., 2:4]'], {}), '(curr_yolo_head[..., 2:4])\n', (1895, 1921), True, 'import tensorflow.keras.backend as K\n'), ((4469, 4505), 'numpy.count_nonzero', 'np.count_nonzero', (['curr_mask_detected'], {}), '(curr_mask_detected)\n', (4485, 4505), True, 'import numpy as np\n'), ((4783, 4874), 'utils.non_max_suppression.classic_non_max_suppression', 'classic_non_max_suppression', (['curr_detected_objects', 'curr_detected_scores', 'nms_threshold'], {}), '(curr_detected_objects, curr_detected_scores,\n nms_threshold)\n', (4810, 4874), False, 'from utils.non_max_suppression import classic_non_max_suppression\n'), ((7326, 7350), 'tensorflow.keras.backend.reshape', 'K.reshape', (['left', '[-1, 1]'], {}), '(left, [-1, 1])\n', (7335, 7350), True, 'import tensorflow.keras.backend as K\n'), ((7360, 7383), 'tensorflow.keras.backend.reshape', 'K.reshape', (['top', '[-1, 1]'], {}), '(top, [-1, 1])\n', (7369, 7383), True, 'import tensorflow.keras.backend as K\n'), ((7393, 7418), 'tensorflow.keras.backend.reshape', 'K.reshape', (['right', '[-1, 1]'], {}), '(right, [-1, 1])\n', (7402, 7418), True, 'import tensorflow.keras.backend as K\n'), ((7428, 7454), 'tensorflow.keras.backend.reshape', 'K.reshape', (['bottom', '[-1, 1]'], {}), '(bottom, [-1, 1])\n', (7437, 7454), True, 'import tensorflow.keras.backend as K\n'), ((1653, 1676), 'tensorflow.keras.backend.dtype', 'K.dtype', (['curr_yolo_head'], {}), '(curr_yolo_head)\n', (1660, 1676), True, 'import tensorflow.keras.backend as K\n'), ((1759, 1782), 'tensorflow.keras.backend.dtype', 'K.dtype', (['curr_yolo_head'], {}), '(curr_yolo_head)\n', (1766, 1782), True, 'import tensorflow.keras.backend as K\n'), ((1810, 1844), 'tensorflow.keras.backend.sigmoid', 'K.sigmoid', (['curr_yolo_head[..., :2]'], {}), '(curr_yolo_head[..., :2])\n', (1819, 1844), True, 'import tensorflow.keras.backend as K\n'), ((3022, 3040), 'tensorflow.keras.backend.learning_phase', 'K.learning_phase', ([], {}), '()\n', (3038, 3040), True, 'import tensorflow.keras.backend as K\n'), ((2849, 2860), 'time.time', 'time.time', ([], {}), '()\n', (2858, 2860), False, 'import time\n'), ((3094, 3105), 'time.time', 'time.time', ([], {}), '()\n', (3103, 3105), False, 'import time\n')] |
#!/usr/bin/env python3
from pandas_datareader import data
import matplotlib.pyplot as plt
import pandas as pd
import datetime as dt
import urllib.request, json
import os
import numpy as np
import tensorflow as tf
from sklearn.preprocessing import MinMaxScaler
from keras.models import Sequential
from keras.layers import Dense, Dropout, LSTM
api_key = "BY8JL5USPR4S629O"
ticker = "AAL"
# JSON file with all the stock market data for AAL from the last 20 years
url_string = "https://www.alphavantage.co/query?function=TIME_SERIES_DAILY&symbol=%s&outputsize=full&apikey=%s"%(ticker,api_key)
# Save data to this file
file_to_save = 'stock_market_data-%s.csv'%ticker
# If you haven't already saved data,
# Go ahead and grab the data from the url
# And store date, low, high, volume, close, open values to a Pandas DataFrame
if not os.path.exists(file_to_save):
with urllib.request.urlopen(url_string) as url:
data = json.loads(url.read().decode())
# extract stock market data
data = data['Time Series (Daily)']
df = pd.DataFrame(columns=['Date','Low','High','Close','Open'])
for k,v in data.items():
date = dt.datetime.strptime(k, '%Y-%m-%d')
data_row = [date.date(),float(v['3. low']),float(v['2. high']),
float(v['4. close']),float(v['1. open'])]
print('Data saved to : %s'%file_to_save)
df.to_csv(file_to_save)
# If the data is already there, just load it from the CSV
else:
print('File already exists. Loading data from CSV')
df = pd.read_csv(file_to_save)
df['Date'] = pd.to_datetime(df.Date,format='%Y-%m-%d')
df.index = df['Date']
df = df.sort_values('Date')
# plt.figure(figsize=(16,8))
# plt.plot(df['Close'], label='Close Price history')
# plt.show()
# print(df.head())
# print(df.info())
df.drop(['Date','Open','Low','High','Unnamed: 0'],inplace=True,axis=1)
# print(df.info())
#creating train and test sets
dataset = df.values
train = dataset[0:2500,:]
valid = dataset[2500:,:]
#converting dataset into x_train and y_train
scaler = MinMaxScaler(feature_range=(0, 1))
scaled_data = scaler.fit_transform(dataset)
x_train, y_train = [], []
for i in range(60,len(train)):
x_train.append(scaled_data[i-60:i,0])
y_train.append(scaled_data[i,0])
x_train, y_train = np.array(x_train), np.array(y_train)
x_train = np.reshape(x_train, (x_train.shape[0],x_train.shape[1],1))
print(1)
# create and fit the LSTM network
model = Sequential()
model.add(LSTM(units=50, return_sequences=True, input_shape=(x_train.shape[1],1)))
model.add(LSTM(units=50))
model.add(Dense(1))
print(2)
model.compile(loss='mean_squared_error', optimizer='adam')
print(3)
model.fit(x_train, y_train, epochs=1, batch_size=1, verbose=2)
# model.save("model.h5", overwrite=True, include_optimizer=True)
print(4)
inputs = df[len(df) - len(valid) - 60:].values
for i in range(2):
#using past 60 from the train data
inputs = np.vstack([inputs,0])
inputs_trans = inputs.reshape(-1,1)
inputs_trans = scaler.transform(inputs_trans)
X_test = []
#iterate starting from 60 since we are using 60 values from training dataset to input.shape[0] is the size of out training data
for i in range(60,inputs_trans.shape[0]):
X_test.append(inputs_trans[i-60:i,0])
X_test = np.array(X_test)
X_test = np.reshape(X_test, (X_test.shape[0],X_test.shape[1],1))
closing_price = model.predict(X_test)
closing_price = scaler.inverse_transform(closing_price)
leng = len(inputs)-1
# print(leng)
inputs = np.delete(inputs,(leng),axis=0)
inputs = np.vstack([inputs,closing_price[-1]])
# closing_price = np.vstack([closing_price,0])
print(closing_price)
# print(inputs)
print(len(inputs))
print(len(closing_price))
# rms=np.sqrt(np.mean(np.power((valid-closing_price),2)))
# print(rms)
ts = pd.to_datetime("2019-01-16",format='%Y-%m-%d')
new_row = pd.DataFrame([[None]], columns = ["Close"], index=[ts])
df = pd.concat([df, pd.DataFrame(new_row)], ignore_index=False)
ts = pd.to_datetime("2019-01-17",format='%Y-%m-%d')
new_row = pd.DataFrame([[None]], columns = ["Close"], index=[ts])
df = pd.concat([df, pd.DataFrame(new_row)], ignore_index=False)
train = df[:2500]
valid = df[2500:]
valid['Predictions'] = closing_price
plt.plot(train['Close'])
plt.plot(valid[['Close','Predictions']])
plt.show()
print(valid) | [
"pandas.DataFrame",
"matplotlib.pyplot.show",
"matplotlib.pyplot.plot",
"pandas.read_csv",
"keras.layers.LSTM",
"sklearn.preprocessing.MinMaxScaler",
"os.path.exists",
"datetime.datetime.strptime",
"keras.layers.Dense",
"pandas.to_datetime",
"numpy.reshape",
"numpy.array",
"pandas_datareader... | [((1606, 1648), 'pandas.to_datetime', 'pd.to_datetime', (['df.Date'], {'format': '"""%Y-%m-%d"""'}), "(df.Date, format='%Y-%m-%d')\n", (1620, 1648), True, 'import pandas as pd\n'), ((2087, 2121), 'sklearn.preprocessing.MinMaxScaler', 'MinMaxScaler', ([], {'feature_range': '(0, 1)'}), '(feature_range=(0, 1))\n', (2099, 2121), False, 'from sklearn.preprocessing import MinMaxScaler\n'), ((2370, 2430), 'numpy.reshape', 'np.reshape', (['x_train', '(x_train.shape[0], x_train.shape[1], 1)'], {}), '(x_train, (x_train.shape[0], x_train.shape[1], 1))\n', (2380, 2430), True, 'import numpy as np\n'), ((2482, 2494), 'keras.models.Sequential', 'Sequential', ([], {}), '()\n', (2492, 2494), False, 'from keras.models import Sequential\n'), ((3902, 3949), 'pandas.to_datetime', 'pd.to_datetime', (['"""2019-01-16"""'], {'format': '"""%Y-%m-%d"""'}), "('2019-01-16', format='%Y-%m-%d')\n", (3916, 3949), True, 'import pandas as pd\n'), ((3959, 4012), 'pandas.DataFrame', 'pd.DataFrame', (['[[None]]'], {'columns': "['Close']", 'index': '[ts]'}), "([[None]], columns=['Close'], index=[ts])\n", (3971, 4012), True, 'import pandas as pd\n'), ((4085, 4132), 'pandas.to_datetime', 'pd.to_datetime', (['"""2019-01-17"""'], {'format': '"""%Y-%m-%d"""'}), "('2019-01-17', format='%Y-%m-%d')\n", (4099, 4132), True, 'import pandas as pd\n'), ((4142, 4195), 'pandas.DataFrame', 'pd.DataFrame', (['[[None]]'], {'columns': "['Close']", 'index': '[ts]'}), "([[None]], columns=['Close'], index=[ts])\n", (4154, 4195), True, 'import pandas as pd\n'), ((4340, 4364), 'matplotlib.pyplot.plot', 'plt.plot', (["train['Close']"], {}), "(train['Close'])\n", (4348, 4364), True, 'import matplotlib.pyplot as plt\n'), ((4365, 4406), 'matplotlib.pyplot.plot', 'plt.plot', (["valid[['Close', 'Predictions']]"], {}), "(valid[['Close', 'Predictions']])\n", (4373, 4406), True, 'import matplotlib.pyplot as plt\n'), ((4406, 4416), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (4414, 4416), True, 'import matplotlib.pyplot as plt\n'), ((833, 861), 'os.path.exists', 'os.path.exists', (['file_to_save'], {}), '(file_to_save)\n', (847, 861), False, 'import os\n'), ((1566, 1591), 'pandas.read_csv', 'pd.read_csv', (['file_to_save'], {}), '(file_to_save)\n', (1577, 1591), True, 'import pandas as pd\n'), ((2322, 2339), 'numpy.array', 'np.array', (['x_train'], {}), '(x_train)\n', (2330, 2339), True, 'import numpy as np\n'), ((2341, 2358), 'numpy.array', 'np.array', (['y_train'], {}), '(y_train)\n', (2349, 2358), True, 'import numpy as np\n'), ((2505, 2577), 'keras.layers.LSTM', 'LSTM', ([], {'units': '(50)', 'return_sequences': '(True)', 'input_shape': '(x_train.shape[1], 1)'}), '(units=50, return_sequences=True, input_shape=(x_train.shape[1], 1))\n', (2509, 2577), False, 'from keras.layers import Dense, Dropout, LSTM\n'), ((2588, 2602), 'keras.layers.LSTM', 'LSTM', ([], {'units': '(50)'}), '(units=50)\n', (2592, 2602), False, 'from keras.layers import Dense, Dropout, LSTM\n'), ((2614, 2622), 'keras.layers.Dense', 'Dense', (['(1)'], {}), '(1)\n', (2619, 2622), False, 'from keras.layers import Dense, Dropout, LSTM\n'), ((2963, 2985), 'numpy.vstack', 'np.vstack', (['[inputs, 0]'], {}), '([inputs, 0])\n', (2972, 2985), True, 'import numpy as np\n'), ((3345, 3361), 'numpy.array', 'np.array', (['X_test'], {}), '(X_test)\n', (3353, 3361), True, 'import numpy as np\n'), ((3376, 3433), 'numpy.reshape', 'np.reshape', (['X_test', '(X_test.shape[0], X_test.shape[1], 1)'], {}), '(X_test, (X_test.shape[0], X_test.shape[1], 1))\n', (3386, 3433), True, 'import numpy as np\n'), ((3594, 3625), 'numpy.delete', 'np.delete', (['inputs', 'leng'], {'axis': '(0)'}), '(inputs, leng, axis=0)\n', (3603, 3625), True, 'import numpy as np\n'), ((3644, 3682), 'numpy.vstack', 'np.vstack', (['[inputs, closing_price[-1]]'], {}), '([inputs, closing_price[-1]])\n', (3653, 3682), True, 'import numpy as np\n'), ((1054, 1116), 'pandas.DataFrame', 'pd.DataFrame', ([], {'columns': "['Date', 'Low', 'High', 'Close', 'Open']"}), "(columns=['Date', 'Low', 'High', 'Close', 'Open'])\n", (1066, 1116), True, 'import pandas as pd\n'), ((1132, 1144), 'pandas_datareader.data.items', 'data.items', ([], {}), '()\n', (1142, 1144), False, 'from pandas_datareader import data\n'), ((4035, 4056), 'pandas.DataFrame', 'pd.DataFrame', (['new_row'], {}), '(new_row)\n', (4047, 4056), True, 'import pandas as pd\n'), ((4218, 4239), 'pandas.DataFrame', 'pd.DataFrame', (['new_row'], {}), '(new_row)\n', (4230, 4239), True, 'import pandas as pd\n'), ((1165, 1200), 'datetime.datetime.strptime', 'dt.datetime.strptime', (['k', '"""%Y-%m-%d"""'], {}), "(k, '%Y-%m-%d')\n", (1185, 1200), True, 'import datetime as dt\n')] |
import numpy as np
from .ising import IsingModel, IsingKernel
from ._paths import potts_energy, potts_sample
class PottsHistogram(object):
def __init__(self, L):
bins = range(-2*L**2, 1)
for i in range(3):
del bins[1]
del bins[2]
self.E = np.array(bins)
self._axis = np.append(self.E-0.1, self.E[-1]+0.1)
def __call__(self, E):
return np.histogram(E.flatten(), self._axis)[0]
class PottsModel(IsingModel):
def __init__(self, L, Q, beta=1.):
super(PottsModel, self).__init__(L, beta)
self.Q = int(Q)
def energy(self, x):
return self.beta * potts_energy(self.L, x)
def sample(self, x=None, n=1, beta=None):
beta = self.beta if beta is None else float(beta)
if beta == 0.:
x = np.random.randint(0,self.Q,self.L**2,dtype='i')
return np.ascontiguousarray(x)
else:
x = x.copy() if x is not None else self.sample(beta=0.)
m = potts_sample(float(beta), int(n), self.L, self.Q, x)
return x
class PottsKernel(IsingKernel):
def __init__(self, L, Q, beta, n=1):
super(PottsKernel, self).__init__(L, beta, n)
self._stationary = PottsModel(L, Q, beta)
| [
"numpy.append",
"numpy.ascontiguousarray",
"numpy.random.randint",
"numpy.array"
] | [((292, 306), 'numpy.array', 'np.array', (['bins'], {}), '(bins)\n', (300, 306), True, 'import numpy as np\n'), ((328, 369), 'numpy.append', 'np.append', (['(self.E - 0.1)', '(self.E[-1] + 0.1)'], {}), '(self.E - 0.1, self.E[-1] + 0.1)\n', (337, 369), True, 'import numpy as np\n'), ((837, 889), 'numpy.random.randint', 'np.random.randint', (['(0)', 'self.Q', '(self.L ** 2)'], {'dtype': '"""i"""'}), "(0, self.Q, self.L ** 2, dtype='i')\n", (854, 889), True, 'import numpy as np\n'), ((904, 927), 'numpy.ascontiguousarray', 'np.ascontiguousarray', (['x'], {}), '(x)\n', (924, 927), True, 'import numpy as np\n')] |
# Packages
import numpy as np
import pandas as pd
import random
random.seed(100)
#~~~~~TEAM FUNCTIONS~~~~~
def get_team_data(data, teamList):
"""
derives probability of player being selected to take free throw, 2 pointer, or three pointer
returns a data frame of team stats and respective probabilities
"""
# Filter data
df = data[data['bbref_id'].isin(teamList)].copy()
# Generate composite ranking
df['2P_Rank'] = (df['2P%'].rank(ascending=False) * df['2P'].rank(ascending=False)).rank(method='first')
df['3P_Rank'] = (df['3P%'].rank(ascending=False) * df['3P'].rank(ascending=False)).rank(method='first')
df['FT_Rank'] = (df['FT%'].rank(ascending=False) * df['FT'].rank(ascending=False)).rank(method='first')
# Get probability of being shooter
probDict = {
1.0 : 0.6,
2.0 : 0.8,
3.0 : 0.9,
4.0 : 0.95,
5.0 : 1.0
}
# map probabilities
df['2P_prob'] = df['2P_Rank'].map(probDict)
df['3P_prob'] = df['3P_Rank'].map(probDict)
df['FT_prob'] = df['FT_Rank'].map(probDict)
# Generate output
df = df.loc[:,['Player', 'bbref_id', '2P%', '3P%', 'FT%', '2P_prob', '3P_prob', 'FT_prob', 'ORB', 'DRB']]
return df
def calc_rebounds_pct(df1, df2):
"""
calculates the probability of team1 and team2 getting an offensive rebound
returns a tuple of offensive rebound probabilities
"""
# make coppies
df1_ = df1.copy()
df2_ = df2.copy()
# assign teams
df1_['team'] = 1
df2_['team'] = 2
# create dataframe
df = pd.concat([df1_, df2_])
df = df.groupby(['team'])[['ORB', 'DRB']].sum()
# calculate rebound probs
team1_ORB_prob = df.iloc[0,0] / (df.iloc[0,0] + df.iloc[1,1])
team2_ORB_prob = df.iloc[1,0] / (df.iloc[1,0] + df.iloc[0,1])
return team1_ORB_prob, team2_ORB_prob
#~~~~~EVENT FUNCTIONS~~~~~
def timeTaken(timeLeft, mu, sigma):
"""
calculates how much time is utilized for an event (shot) using normal distribution
returns a float of seconds used
"""
t = np.random.normal(mu, sigma)
shotClock = 24
minTime = 0.3
# force t to be valid time
if t < minTime:
t = minTime
elif t > timeLeft or t > shotClock:
t = min(timeLeft, shotClock)
return t
def takeShot(shotType, timeLeft, makePct=0.45, offRebPct=0.25, points=0, maximize='N'):
"""
calculates the outcome of a shot
returns a tuple of time remaining, points scored, and who has possession of the ball
"""
# Exception handling
if timeLeft == 0:
# print('no time left')
return 0, 0, 'opp'
# Determine how much time is taken
mu, sigma = 4, 1.5
# if team wants to maximize time used
if maximize == 'Y':
mu = timeLeft - 1.5
t = timeTaken(timeLeft, mu, sigma)
# Determine if points scored
rand = random.random()
if rand <= makePct:
points += shotType
timeLeft -= t
poss = 'opp'
# print('made', str(shotType))
else:
timeLeft -= t
# rebound
rand = random.random()
if rand <= offRebPct:
poss = 'keep'
# print('missed', str(shotType), 'w/ rebound')
else:
poss = 'opp'
# print('missed', str(shotType), 'w/o rebound')
# hardcoded rebound time
timeLeft -= 0.5
if timeLeft < 0:
timeLeft = 0
return timeLeft, points, poss
def foul(timeLeft, ftType=2, makePct=0.8, ftRebPct=0.15, points=0):
"""
calculates the time it takes to foul and outcome of subsequent free throws
returns a tuple of time left, points scored, and who has possession of the ball
"""
# Determine how much time is taken
mu, sigma = 2, 1.5
t = timeTaken(timeLeft, mu, sigma)
timeLeft -= t
if timeLeft < 0:
return 0, 0, 'opp'
# Determine if points scored
# first free throw
rand = random.random()
if rand <= makePct:
points = 1
# print('made ft 1')
elif ftType==1:
rand = random.random()
if rand <= ftRebPct:
poss = 'keep'
# print('missed front 1:1 w/ rebound')
else:
poss = 'opp'
# print('missed front 1:1 w/o rebound')
# hardcoded rebound time
timeLeft -= 0.5
if timeLeft < 0:
timeLeft = 0
else:
# print('missed ft 1')
pass
# if 1:1 free throw
if ftType == 1:
if points == 0:
rand = random.random()
if rand <= ftRebPct:
poss = 'keep'
# print('missed ft 2 w/ rebound')
else:
poss = 'opp'
# print('missed ft 2 w/o rebound')
return timeLeft, points, poss
# second free throw
rand = random.random()
if rand <= makePct:
points += 1
poss = 'opp'
# print('made ft 2')
else:
rand = random.random()
if rand <= ftRebPct:
poss = 'keep'
# print('missed ft 2 w/ rebound')
else:
poss = 'opp'
# print('missed ft 2 w/o rebound')
# hardcoded rebound time
timeLeft -= 0.5
if timeLeft < 0:
timeLeft = 0
return timeLeft, points, poss
def calc_shot_prob(df, shot):
"""
calculates the probability of a shot being made
returns a float object of probability
"""
df = df.copy()
rand = random.random()
# Calculate probability
# free throw
if shot == 1:
# determine shooter
df = df.sort_values(['FT_prob'])
df['shooter'] = np.where(df['FT_prob']>=rand, 1, 0)
df = df[df['shooter']==1].iloc[0]
shooter = df.loc['bbref_id']
# determine prob
prob = df.loc['FT%']
# print(shot, shooter, prob)
# 2 pointer
elif shot == 2:
# determine shooter
df = df.sort_values(['2P_prob'])
df['shooter'] = np.where(df['2P_prob']>=rand, 1, 0)
df = df[df['shooter']==1].iloc[0]
shooter = df.loc['bbref_id']
# determine prob
prob = df.loc['2P%']
# print(shot, shooter, prob)
# 3 pointer
elif shot == 3:
# determine shooter
df = df.sort_values(['3P_prob'])
df['shooter'] = np.where(df['3P_prob']>=rand, 1, 0)
df = df[df['shooter']==1].iloc[0]
shooter = df.loc['bbref_id']
# determine prob
prob = df.loc['3P%']
# print(shot, shooter, prob)
return prob
#~~~~~SIMULATION FUNCTIONS~~~~~
def prepSim(team1, team2):
"""
helper function to prepare initial data for simulations
returns a tuple of dataframe object of stats for each team and float object of offensive rebound probability for each team
"""
# Get data
cols = ['Player', 'bbref_id', '2P', '2PA', '2P%', '3P', '3PA', '3P%', 'FT', 'FTA', 'FT%', 'ORB', 'DRB']
data = pd.read_csv('./player_data.csv', usecols=cols)
# Teams
df1 = get_team_data(data, team1)
df2 = get_team_data(data, team2)
# Rebound probability
rbPct1, rbPct2 = calc_rebounds_pct(df1, df2)
return df1, df2, rbPct1, rbPct2
def runSim(strategy, df1, df2, rbPct1, rbPct2, timeLeftInitial=30, pointDiffInitial=-3, teamFouls1Initial=5, teamFouls2Initial=5, overtimeProb=0.5):
# Initialize values
timeLeft = timeLeftInitial
pointDiff = pointDiffInitial
# nba reach double if 2 fouls in last 2:00 of quarter otherwise 5
teamFouls1 = max(teamFouls1Initial, 3) # ensures bonus after 2 fouls if value less than 5 selected
teamFouls2 = max(teamFouls2Initial, 3)
# Run simulation
while timeLeft > 0:
# our team
poss = 'keep'
# keep shooting while maintaining possession
while poss == 'keep':
# print('us', timeLeft, pointDiff)
# losing or tied
if pointDiff <= 0:
# losing
if pointDiff < 0:
# print('losing')
shotProb = calc_shot_prob(df1, strategy)
# print('shot prob', shotProb)
timeLeft, points, poss = takeShot(strategy, timeLeft, shotProb, rbPct1)
pointDiff += points
# print(timeLeft, pointDiff, poss)
# tied
else:
# print('tied and maximizing')
shotProb = calc_shot_prob(df1, 2)
# print('shot prob', shotProb)
timeLeft, points, poss = takeShot(2, timeLeft, shotProb, rbPct1, maximize='Y') # always take 2 when tied
pointDiff += points
# print(timeLeft, pointDiff, poss)
# winning
else:
# print('winning and free throws')
shotProb = calc_shot_prob(df1, 1)
# print('shot prob', shotProb)
# double bonus
if teamFouls1 >= 5:
# print('2 FT')
timeLeft, points, poss = foul(timeLeft, 2, shotProb, rbPct1*0.8) # lowered due to ft rebounds being harder
pointDiff += points
teamFouls2 += 1
# print(timeLeft, pointDiff, poss)
# 1 & 1
else:
# print('1:1')
timeLeft, points, poss = foul(timeLeft, 1, shotProb, rbPct1*0.8)
pointDiff += points
teamFouls2 += 1
# print(timeLeft, pointDiff, poss)
# print()
# opponent
# break loop if no time remaining
if timeLeft == 0:
break
poss = 'keep'
# keep shooting while maintaining possession
while poss == 'keep':
# print('them', timeLeft, pointDiff)
# losing or tied
if pointDiff >= 0:
# losing
if pointDiff > 0:
# print('losing')
shotProb = calc_shot_prob(df2, strategy)
# print('shot prob', shotProb)
timeLeft, points, poss = takeShot(strategy, timeLeft, shotProb, rbPct2)
pointDiff -= points
# print(timeLeft, pointDiff, poss)
# tied
else:
# print('tied and maximizing')
shotProb = calc_shot_prob(df2, 2)
timeLeft, points, poss = takeShot(2, timeLeft, shotProb, rbPct2, maximize='Y')
pointDiff -= points
# print(timeLeft, pointDiff, poss)
# winning
else:
# print('winning and free throws')
shotProb = calc_shot_prob(df1, 1)
# print('shot prob', shotProb)
# double bonus
if teamFouls1 >= 5:
# print('2 FT')
timeLeft, points, poss = foul(timeLeft, 2, shotProb, rbPct2*0.8)
pointDiff -= points
teamFouls1 += 1
# print(timeLeft, pointDiff, poss)
# 1 & 1
else:
# print('1:1')
timeLeft, points, poss = foul(timeLeft, 1, shotProb, rbPct1*0.8)
pointDiff -= points
teamFouls1 += 1
# print(timeLeft, pointDiff, poss)
# print()
# Determine result
if pointDiff > 0:
result = 1
overtime = 0
elif pointDiff < 0:
result = 0
overtime = 0
else:
rand = random.random()
if rand <= overtimeProb:
result = 1
else:
result = 0
overtime = 1
return result, overtime, pointDiff
| [
"pandas.read_csv",
"random.random",
"numpy.where",
"random.seed",
"numpy.random.normal",
"pandas.concat"
] | [((72, 88), 'random.seed', 'random.seed', (['(100)'], {}), '(100)\n', (83, 88), False, 'import random\n'), ((1642, 1665), 'pandas.concat', 'pd.concat', (['[df1_, df2_]'], {}), '([df1_, df2_])\n', (1651, 1665), True, 'import pandas as pd\n'), ((2158, 2185), 'numpy.random.normal', 'np.random.normal', (['mu', 'sigma'], {}), '(mu, sigma)\n', (2174, 2185), True, 'import numpy as np\n'), ((3004, 3019), 'random.random', 'random.random', ([], {}), '()\n', (3017, 3019), False, 'import random\n'), ((4132, 4147), 'random.random', 'random.random', ([], {}), '()\n', (4145, 4147), False, 'import random\n'), ((5061, 5076), 'random.random', 'random.random', ([], {}), '()\n', (5074, 5076), False, 'import random\n'), ((5752, 5767), 'random.random', 'random.random', ([], {}), '()\n', (5765, 5767), False, 'import random\n'), ((7275, 7321), 'pandas.read_csv', 'pd.read_csv', (['"""./player_data.csv"""'], {'usecols': 'cols'}), "('./player_data.csv', usecols=cols)\n", (7286, 7321), True, 'import pandas as pd\n'), ((3229, 3244), 'random.random', 'random.random', ([], {}), '()\n', (3242, 3244), False, 'import random\n'), ((5202, 5217), 'random.random', 'random.random', ([], {}), '()\n', (5215, 5217), False, 'import random\n'), ((5932, 5969), 'numpy.where', 'np.where', (["(df['FT_prob'] >= rand)", '(1)', '(0)'], {}), "(df['FT_prob'] >= rand, 1, 0)\n", (5940, 5969), True, 'import numpy as np\n'), ((4260, 4275), 'random.random', 'random.random', ([], {}), '()\n', (4273, 4275), False, 'import random\n'), ((4744, 4759), 'random.random', 'random.random', ([], {}), '()\n', (4757, 4759), False, 'import random\n'), ((6281, 6318), 'numpy.where', 'np.where', (["(df['2P_prob'] >= rand)", '(1)', '(0)'], {}), "(df['2P_prob'] >= rand, 1, 0)\n", (6289, 6318), True, 'import numpy as np\n'), ((12190, 12205), 'random.random', 'random.random', ([], {}), '()\n', (12203, 12205), False, 'import random\n'), ((6630, 6667), 'numpy.where', 'np.where', (["(df['3P_prob'] >= rand)", '(1)', '(0)'], {}), "(df['3P_prob'] >= rand, 1, 0)\n", (6638, 6667), True, 'import numpy as np\n')] |
"""
Hough Circle Transform
- find circles in an image
function: cv2.HoughCircles()
circle represented mathematically as (x - x_center)^2 + (y - y_center)^2 = r^2
(x_center, y_center) is center of circle
r is radius of circle
3 parameters -> need 3D accumulator for hough transform
likely ineffective
OpenCV uses Hough Gradient method
uses gradient info of edges
function is cv2.HoughCircles()
many arguments; see documentation
"""
import cv2
import numpy as np
img = cv2.imread('opencv_logo.png', 0)
img = cv2.medianBlur(img, 5)
cimg = cv2.cvtColor(img, cv2.COLOR_GRAY2BGR)
circles = cv2.HoughCircles(img, cv2.HOUGH_GRADIENT, 1, 20, param1 = 50, param2 = 30, minRadius = 0, maxRadius = 0)
circles = np.uint8(np.around(circles))
for i in circles[0, :]:
# draw the outer circle
cv2.circle(cimg, (i[0], i[1]), i[2], (0, 255, 0), 2)
# draw the center of the circle
cv2.circle(cimg, (i[0], i[1]), 2, (0, 0, 255), 3)
cv2.imshow('detected circles', cimg)
cv2.waitKey(0)
cv2.destroyAllWindows()
| [
"cv2.HoughCircles",
"cv2.circle",
"cv2.medianBlur",
"cv2.cvtColor",
"cv2.waitKey",
"cv2.destroyAllWindows",
"cv2.imread",
"numpy.around",
"cv2.imshow"
] | [((490, 522), 'cv2.imread', 'cv2.imread', (['"""opencv_logo.png"""', '(0)'], {}), "('opencv_logo.png', 0)\n", (500, 522), False, 'import cv2\n'), ((529, 551), 'cv2.medianBlur', 'cv2.medianBlur', (['img', '(5)'], {}), '(img, 5)\n', (543, 551), False, 'import cv2\n'), ((559, 596), 'cv2.cvtColor', 'cv2.cvtColor', (['img', 'cv2.COLOR_GRAY2BGR'], {}), '(img, cv2.COLOR_GRAY2BGR)\n', (571, 596), False, 'import cv2\n'), ((608, 708), 'cv2.HoughCircles', 'cv2.HoughCircles', (['img', 'cv2.HOUGH_GRADIENT', '(1)', '(20)'], {'param1': '(50)', 'param2': '(30)', 'minRadius': '(0)', 'maxRadius': '(0)'}), '(img, cv2.HOUGH_GRADIENT, 1, 20, param1=50, param2=30,\n minRadius=0, maxRadius=0)\n', (624, 708), False, 'import cv2\n'), ((953, 989), 'cv2.imshow', 'cv2.imshow', (['"""detected circles"""', 'cimg'], {}), "('detected circles', cimg)\n", (963, 989), False, 'import cv2\n'), ((990, 1004), 'cv2.waitKey', 'cv2.waitKey', (['(0)'], {}), '(0)\n', (1001, 1004), False, 'import cv2\n'), ((1005, 1028), 'cv2.destroyAllWindows', 'cv2.destroyAllWindows', ([], {}), '()\n', (1026, 1028), False, 'import cv2\n'), ((733, 751), 'numpy.around', 'np.around', (['circles'], {}), '(circles)\n', (742, 751), True, 'import numpy as np\n'), ((809, 861), 'cv2.circle', 'cv2.circle', (['cimg', '(i[0], i[1])', 'i[2]', '(0, 255, 0)', '(2)'], {}), '(cimg, (i[0], i[1]), i[2], (0, 255, 0), 2)\n', (819, 861), False, 'import cv2\n'), ((902, 951), 'cv2.circle', 'cv2.circle', (['cimg', '(i[0], i[1])', '(2)', '(0, 0, 255)', '(3)'], {}), '(cimg, (i[0], i[1]), 2, (0, 0, 255), 3)\n', (912, 951), False, 'import cv2\n')] |
import os
import glob
import regex
import numpy as np
import pandas as pd
import nibabel as nib
def find_targeted_files(path):
'''
Find and save files of interest. In this case, we look for short-axis
nifti files.
'''
patt = ['cine_short_axis', 'cine_short_axis_6MM', 'CINE_EC*_apex', 'EC_*_FIL', 'EC_*_10slices',
'CINE_EC_barrido', 'CINE_EC', 'cine_*_EC', 'SHORT_AXIS', 'CINE_EJE_CORTO',
'FUNCION_VI', '*_#SA', '*SAX*', 'sa_cine']
filepaths = []
for p in patt:
filepaths.extend(list(glob.iglob(os.path.join(path, '**', p + '.nii.gz'), recursive=True)))
files = []
for f in sorted(filepaths):
# Skip contour files
if '_label' in f: continue
files.append(f)
return files
def postProcess(path):
'''
Look for short-axis nifti slices and grouped them together in one
4D file.
'''
files = find_targeted_files(path)
if len(files) > 1:
ims = [nib.load(f) for f in files]
mks = [nib.load(regex.sub(r'\.nii', '_label.nii', f)) for f in files]
mkus = [nib.load(regex.sub(r'\.nii', '_label_upsample.nii', f)) for f in files]
zs = pd.Series([im.header.structarr['qoffset_z'] for im in ims])
# Filter new and old slices by mask existence
mask = [np.unique(mk.get_fdata()).size > 1 for mk in mks]
zs = zs[mask]
#zs = zs.drop_duplicates(keep='first')
filt_ims = np.asarray(ims)[zs.index]
filt_mks = np.asarray(mks)[zs.index]
filt_mkus = np.asarray(mkus)[zs.index]
if np.any(np.greater([im.shape[2] for im in ims], 1)):
# There is already a 4D image and repeated slices
# probably due to the quality of the acquisition.
# We try to concatenate them.
print('4D image found already!')
# If only one nifti has mask, skip postprocess
if np.sum(mask) == 1: return 0
# If other nitfis are 4D, skip postprocess as well
if ims[1].get_fdata().ndim > 3: return 0
im1 = ims[0].get_fdata()[:]
mk1 = mks[0].get_fdata()[:]
mku1 = mkus[0].get_fdata()[:]
# List of z positions per slice
im_dict = ims[0].header.structarr
zpos = np.asarray([im_dict['qoffset_z'] + im_dict['srow_z'][2]*i for i in range(ims[0].shape[-2])])
im_array = np.asarray([
*[np.expand_dims(im1[...,i,:], axis=2) for i in range(im1.shape[2])][::-1],
*[ims[i].get_fdata()[:] for i in range(1,len(ims))]
])
newim = np.concatenate(im_array, axis=2)
mk_array = np.asarray([
*[np.expand_dims(mk1[...,i,:], axis=2) for i in range(mk1.shape[2])][::-1],
*[mks[i].get_fdata()[:] for i in range(1,len(mks))]
])
newmk = np.concatenate(mk_array, axis=2)
mku_array = np.asarray([
*[np.expand_dims(mku1[...,i,:], axis=2) for i in range(mku1.shape[2])][::-1],
*[mkus[i].get_fdata()[:] for i in range(1,len(mkus))]
], dtype=np.uint8)
newmku = np.concatenate(mku_array, axis=2)
else:
# All nifti files are 3D and we need to combine them together
print('Set of 3D images found')
newim = np.repeat(np.zeros(ims[0].get_fdata().shape), filt_ims.shape[0], axis=2)
newmk = np.repeat(np.zeros(mks[0].get_fdata().shape), filt_mks.shape[0], axis=2)
newmku = np.repeat(np.zeros(mkus[0].get_fdata().shape, np.float16), filt_mkus.shape[0], axis=2)
oims = filt_ims[np.argsort(zs)]
omks = filt_mks[np.argsort(zs)]
omkus = filt_mkus[np.argsort(zs)]
for i in range(len(oims)):
try:
newim[...,i,:] = oims[i].get_fdata().squeeze()[:]
newmk[...,i,:] = omks[i].get_fdata().squeeze()[:]
newmku[...,i,:] = omkus[i].get_fdata().squeeze()[:]
except ValueError: # Shape missmatch
print('ValueError: shape missmatch during post processing'
' for files related to {}'.format(files[0]))
continue
# Post-processed cine short axis
outf = os.path.join(os.path.dirname(files[0]), 'pp_cine_short_axis.nii.gz')
nim = nib.Nifti1Image(newim, None, ims[0].header)
nib.save(nim, outf)
nmk = nib.Nifti1Image(newmk, None, mks[0].header)
nib.save(nmk, regex.sub(r'\.nii', '_label.nii', outf))
nmku = nib.Nifti1Image(newmku, None, mkus[0].header)
nib.save(nmku, regex.sub(r'\.nii', '_label_upsample.nii', outf))
return 1
| [
"nibabel.Nifti1Image",
"numpy.sum",
"nibabel.load",
"numpy.asarray",
"os.path.dirname",
"numpy.greater",
"numpy.expand_dims",
"nibabel.save",
"numpy.argsort",
"regex.sub",
"pandas.Series",
"os.path.join",
"numpy.concatenate"
] | [((1179, 1238), 'pandas.Series', 'pd.Series', (["[im.header.structarr['qoffset_z'] for im in ims]"], {}), "([im.header.structarr['qoffset_z'] for im in ims])\n", (1188, 1238), True, 'import pandas as pd\n'), ((4400, 4443), 'nibabel.Nifti1Image', 'nib.Nifti1Image', (['newim', 'None', 'ims[0].header'], {}), '(newim, None, ims[0].header)\n', (4415, 4443), True, 'import nibabel as nib\n'), ((4452, 4471), 'nibabel.save', 'nib.save', (['nim', 'outf'], {}), '(nim, outf)\n', (4460, 4471), True, 'import nibabel as nib\n'), ((4486, 4529), 'nibabel.Nifti1Image', 'nib.Nifti1Image', (['newmk', 'None', 'mks[0].header'], {}), '(newmk, None, mks[0].header)\n', (4501, 4529), True, 'import nibabel as nib\n'), ((4608, 4653), 'nibabel.Nifti1Image', 'nib.Nifti1Image', (['newmku', 'None', 'mkus[0].header'], {}), '(newmku, None, mkus[0].header)\n', (4623, 4653), True, 'import nibabel as nib\n'), ((972, 983), 'nibabel.load', 'nib.load', (['f'], {}), '(f)\n', (980, 983), True, 'import nibabel as nib\n'), ((1447, 1462), 'numpy.asarray', 'np.asarray', (['ims'], {}), '(ims)\n', (1457, 1462), True, 'import numpy as np\n'), ((1492, 1507), 'numpy.asarray', 'np.asarray', (['mks'], {}), '(mks)\n', (1502, 1507), True, 'import numpy as np\n'), ((1538, 1554), 'numpy.asarray', 'np.asarray', (['mkus'], {}), '(mkus)\n', (1548, 1554), True, 'import numpy as np\n'), ((1583, 1625), 'numpy.greater', 'np.greater', (['[im.shape[2] for im in ims]', '(1)'], {}), '([im.shape[2] for im in ims], 1)\n', (1593, 1625), True, 'import numpy as np\n'), ((2612, 2644), 'numpy.concatenate', 'np.concatenate', (['im_array'], {'axis': '(2)'}), '(im_array, axis=2)\n', (2626, 2644), True, 'import numpy as np\n'), ((2876, 2908), 'numpy.concatenate', 'np.concatenate', (['mk_array'], {'axis': '(2)'}), '(mk_array, axis=2)\n', (2890, 2908), True, 'import numpy as np\n'), ((3162, 3195), 'numpy.concatenate', 'np.concatenate', (['mku_array'], {'axis': '(2)'}), '(mku_array, axis=2)\n', (3176, 3195), True, 'import numpy as np\n'), ((4330, 4355), 'os.path.dirname', 'os.path.dirname', (['files[0]'], {}), '(files[0])\n', (4345, 4355), False, 'import os\n'), ((4552, 4591), 'regex.sub', 'regex.sub', (['"""\\\\.nii"""', '"""_label.nii"""', 'outf'], {}), "('\\\\.nii', '_label.nii', outf)\n", (4561, 4591), False, 'import regex\n'), ((4677, 4725), 'regex.sub', 'regex.sub', (['"""\\\\.nii"""', '"""_label_upsample.nii"""', 'outf'], {}), "('\\\\.nii', '_label_upsample.nii', outf)\n", (4686, 4725), False, 'import regex\n'), ((1024, 1060), 'regex.sub', 'regex.sub', (['"""\\\\.nii"""', '"""_label.nii"""', 'f'], {}), "('\\\\.nii', '_label.nii', f)\n", (1033, 1060), False, 'import regex\n'), ((1103, 1148), 'regex.sub', 'regex.sub', (['"""\\\\.nii"""', '"""_label_upsample.nii"""', 'f'], {}), "('\\\\.nii', '_label_upsample.nii', f)\n", (1112, 1148), False, 'import regex\n'), ((1913, 1925), 'numpy.sum', 'np.sum', (['mask'], {}), '(mask)\n', (1919, 1925), True, 'import numpy as np\n'), ((3650, 3664), 'numpy.argsort', 'np.argsort', (['zs'], {}), '(zs)\n', (3660, 3664), True, 'import numpy as np\n'), ((3694, 3708), 'numpy.argsort', 'np.argsort', (['zs'], {}), '(zs)\n', (3704, 3708), True, 'import numpy as np\n'), ((3740, 3754), 'numpy.argsort', 'np.argsort', (['zs'], {}), '(zs)\n', (3750, 3754), True, 'import numpy as np\n'), ((558, 597), 'os.path.join', 'os.path.join', (['path', '"""**"""', "(p + '.nii.gz')"], {}), "(path, '**', p + '.nii.gz')\n", (570, 597), False, 'import os\n'), ((2435, 2473), 'numpy.expand_dims', 'np.expand_dims', (['im1[..., i, :]'], {'axis': '(2)'}), '(im1[..., i, :], axis=2)\n', (2449, 2473), True, 'import numpy as np\n'), ((2699, 2737), 'numpy.expand_dims', 'np.expand_dims', (['mk1[..., i, :]'], {'axis': '(2)'}), '(mk1[..., i, :], axis=2)\n', (2713, 2737), True, 'import numpy as np\n'), ((2964, 3003), 'numpy.expand_dims', 'np.expand_dims', (['mku1[..., i, :]'], {'axis': '(2)'}), '(mku1[..., i, :], axis=2)\n', (2978, 3003), True, 'import numpy as np\n')] |
import numpy as np
import math
from scipy.special import erfc, erfcinv
def phi(input):
"""Phi function.
:param input:
Float (scalar or array) value.
:returns:
phi(input).
"""
return 0.5 * erfc(-input/np.sqrt(2))
def invphi(input):
"""Inverse phi function.
:param input:
Float (scalar or array) value.
:returns:
invphi(input).
"""
return -1 * np.sqrt(2) * erfcinv(input/0.5)
def calcEmpiricalProbFromValue(G, e, value):
"""Calculate the empirical probability of a given value of loss (fatalities, dollars).
:param G:
Input G statistic.
:param e:
Expected number of losses.
:param value:
Number of losses for which corresponding probability should be calculated.
:returns:
Probability that value will not be exceeded.
"""
e = e + 0.00001
value = value + 0.00001
p = phi((math.log(value) - math.log(e))/G)
return p
def calcEmpiricalValueFromProb(G, e, p):
""" Calculate the loss value given an input probability.
:param G:
Input G statistic.
:param e:
Expected number of losses.
:param p:
Input probability for which corresponding loss value should be calculated.
:returns:
Number of losses.
"""
e = e + 0.00001
value = math.exp(G * invphi(p) + math.log(e))
return value
def calcEmpiricalProbFromRange(G, e, drange):
"""Calculate the empirical probability of a given loss range.
:param G:
Input G statistic.
:param e:
Expected number of losses.
:param drange:
Two-element sequence, containing range of losses over which probability should be calculated.
:returns:
Probability that losses will occur in input range.
"""
e = e + 0.00001
if e < 1:
#e = 0.1
if G > 1.7:
G = 1.7613
if len(drange) == 2:
if (e-0) < 0.001:
e = 0.5
fmin = drange[0] + 0.00001
fmax = drange[1] + 0.00001
p1 = phi((math.log(fmax) - math.log(e))/G)
p2 = phi((math.log(fmin) - math.log(e))/G)
p = p1-p2
return p
else:
psum = 0
for i in range(0, len(drange)-1):
fmax = drange[i+1] + 0.00001
fmin = drange[i] + 0.00001
p1 = phi((math.log(fmax) - math.log(e))/G)
p2 = phi((math.log(fmin) - math.log(e))/G)
psum += (p1-p2)
return psum
| [
"scipy.special.erfcinv",
"math.log",
"numpy.sqrt"
] | [((443, 463), 'scipy.special.erfcinv', 'erfcinv', (['(input / 0.5)'], {}), '(input / 0.5)\n', (450, 463), False, 'from scipy.special import erfc, erfcinv\n'), ((430, 440), 'numpy.sqrt', 'np.sqrt', (['(2)'], {}), '(2)\n', (437, 440), True, 'import numpy as np\n'), ((1370, 1381), 'math.log', 'math.log', (['e'], {}), '(e)\n', (1378, 1381), False, 'import math\n'), ((244, 254), 'numpy.sqrt', 'np.sqrt', (['(2)'], {}), '(2)\n', (251, 254), True, 'import numpy as np\n'), ((927, 942), 'math.log', 'math.log', (['value'], {}), '(value)\n', (935, 942), False, 'import math\n'), ((945, 956), 'math.log', 'math.log', (['e'], {}), '(e)\n', (953, 956), False, 'import math\n'), ((2063, 2077), 'math.log', 'math.log', (['fmax'], {}), '(fmax)\n', (2071, 2077), False, 'import math\n'), ((2080, 2091), 'math.log', 'math.log', (['e'], {}), '(e)\n', (2088, 2091), False, 'import math\n'), ((2114, 2128), 'math.log', 'math.log', (['fmin'], {}), '(fmin)\n', (2122, 2128), False, 'import math\n'), ((2131, 2142), 'math.log', 'math.log', (['e'], {}), '(e)\n', (2139, 2142), False, 'import math\n'), ((2353, 2367), 'math.log', 'math.log', (['fmax'], {}), '(fmax)\n', (2361, 2367), False, 'import math\n'), ((2370, 2381), 'math.log', 'math.log', (['e'], {}), '(e)\n', (2378, 2381), False, 'import math\n'), ((2408, 2422), 'math.log', 'math.log', (['fmin'], {}), '(fmin)\n', (2416, 2422), False, 'import math\n'), ((2425, 2436), 'math.log', 'math.log', (['e'], {}), '(e)\n', (2433, 2436), False, 'import math\n')] |
"""
Script calculates Eurasian snow index for October-November following the
methods of Peings et al. 2017
Notes
-----
Author : <NAME>
Date : 22 July 2019
"""
### Import modules
import datetime
import numpy as np
import matplotlib.pyplot as plt
import read_MonthlyData as MOM
import calc_Utilities as UT
import scipy.stats as sts
import scipy.signal as SS
import read_Reanalysis as MOR
### Define directories
directoryfigure = '/home/zlabe/Desktop/'
directoryoutput = '/home/zlabe/Documents/Research/AMIP/Data/'
### Define time
now = datetime.datetime.now()
currentmn = str(now.month)
currentdy = str(now.day)
currentyr = str(now.year)
currenttime = currentmn + '_' + currentdy + '_' + currentyr
titletime = currentmn + '/' + currentdy + '/' + currentyr
print('\n' '----Calculating Snow Cover Index - %s----' % titletime)
#### Alott time series
year1 = 1979
year2 = 2015
years = np.arange(year1,year2+1,1)
### Add parameters
ensembles = 10
varnames = 'SWE'
runnames = [r'ERA-I',r'CSST',r'CSIC',r'AMIP',r'AMQ',r'AMS',r'AMQS']
runnamesm = [r'CSST',r'CSIC',r'AMIP',r'AMQ',r'AMS',r'AMQS']
def readVar(varnames,runnamesm):
### Call function to read in ERA-Interim
lat,lon,time,lev,era = MOR.readDataR('T2M','surface',False,True)
### Call functions to read in WACCM data
models = np.empty((len(runnamesm),ensembles,era.shape[0],era.shape[1],
era.shape[2],era.shape[3]))
for i in range(len(runnamesm)):
lat,lon,time,lev,models[i] = MOM.readDataM(varnames,runnamesm[i],
'surface',False,True)
### Select October-November for index
modq = np.nanmean(models[:,:,:,9:11,:,:],axis=3)
### Calculate ensemble mean
modmean = np.nanmean(modq[:,:,:,:,:],axis=1)
return modmean,lat,lon,lev
###############################################################################
### Read in data functions
mod,lat,lon,lev = readVar(varnames,runnamesm)
### Slice over region of interest for Eurasia (40-80N,35-180E)
latq = np.where((lat >= 40) & (lat <= 80))[0]
lonq = np.where((lon >= 35) & (lon <=180))[0]
latn = lat[latq]
lonn = lon[lonq]
lon2,lat2 = np.meshgrid(lonn,latn)
modlat = mod[:,:,latq,:]
modlon = modlat[:,:,:,lonq]
modslice = modlon.copy()
### Consider years 1979-2015
modsliceq = modslice[:,:-1]
### Calculate average snow index
snowindex = UT.calc_weightedAve(modsliceq,lat2)
### Calculate detrended snow index
snowindexdt = SS.detrend(snowindex,type='linear',axis=1)
### Save both indices
np.savetxt(directoryoutput + 'SWE_Eurasia_ON.txt',
np.vstack([years,snowindex]).transpose(),delimiter=',',fmt='%3.1f',
footer='\n Snow cover index calculated for each' \
'\n experiment [CSST,CSIC,AMIP,AMQ,AMS,AMQS]\n' \
' in Oct-Nov',newline='\n\n')
np.savetxt(directoryoutput + 'SWE_Eurasia_ON_DETRENDED.txt',
np.vstack([years,snowindexdt]).transpose(),delimiter=',',fmt='%3.1f',
footer='\n Snow cover index calculated for each' \
'\n experiment [CSST,CSIC,AMIP,AMQ,AMS,AMQS]\n' \
' in Oct-Nov ---> detrended data',newline='\n\n') | [
"read_Reanalysis.readDataR",
"numpy.meshgrid",
"numpy.where",
"numpy.arange",
"read_MonthlyData.readDataM",
"scipy.signal.detrend",
"calc_Utilities.calc_weightedAve",
"datetime.datetime.now",
"numpy.vstack",
"numpy.nanmean"
] | [((560, 583), 'datetime.datetime.now', 'datetime.datetime.now', ([], {}), '()\n', (581, 583), False, 'import datetime\n'), ((906, 936), 'numpy.arange', 'np.arange', (['year1', '(year2 + 1)', '(1)'], {}), '(year1, year2 + 1, 1)\n', (915, 936), True, 'import numpy as np\n'), ((2206, 2229), 'numpy.meshgrid', 'np.meshgrid', (['lonn', 'latn'], {}), '(lonn, latn)\n', (2217, 2229), True, 'import numpy as np\n'), ((2412, 2448), 'calc_Utilities.calc_weightedAve', 'UT.calc_weightedAve', (['modsliceq', 'lat2'], {}), '(modsliceq, lat2)\n', (2431, 2448), True, 'import calc_Utilities as UT\n'), ((2498, 2542), 'scipy.signal.detrend', 'SS.detrend', (['snowindex'], {'type': '"""linear"""', 'axis': '(1)'}), "(snowindex, type='linear', axis=1)\n", (2508, 2542), True, 'import scipy.signal as SS\n'), ((1215, 1259), 'read_Reanalysis.readDataR', 'MOR.readDataR', (['"""T2M"""', '"""surface"""', '(False)', '(True)'], {}), "('T2M', 'surface', False, True)\n", (1228, 1259), True, 'import read_Reanalysis as MOR\n'), ((1678, 1725), 'numpy.nanmean', 'np.nanmean', (['models[:, :, :, 9:11, :, :]'], {'axis': '(3)'}), '(models[:, :, :, 9:11, :, :], axis=3)\n', (1688, 1725), True, 'import numpy as np\n'), ((1771, 1810), 'numpy.nanmean', 'np.nanmean', (['modq[:, :, :, :, :]'], {'axis': '(1)'}), '(modq[:, :, :, :, :], axis=1)\n', (1781, 1810), True, 'import numpy as np\n'), ((2075, 2110), 'numpy.where', 'np.where', (['((lat >= 40) & (lat <= 80))'], {}), '((lat >= 40) & (lat <= 80))\n', (2083, 2110), True, 'import numpy as np\n'), ((2121, 2157), 'numpy.where', 'np.where', (['((lon >= 35) & (lon <= 180))'], {}), '((lon >= 35) & (lon <= 180))\n', (2129, 2157), True, 'import numpy as np\n'), ((1506, 1567), 'read_MonthlyData.readDataM', 'MOM.readDataM', (['varnames', 'runnamesm[i]', '"""surface"""', '(False)', '(True)'], {}), "(varnames, runnamesm[i], 'surface', False, True)\n", (1519, 1567), True, 'import read_MonthlyData as MOM\n'), ((2626, 2655), 'numpy.vstack', 'np.vstack', (['[years, snowindex]'], {}), '([years, snowindex])\n', (2635, 2655), True, 'import numpy as np\n'), ((2930, 2961), 'numpy.vstack', 'np.vstack', (['[years, snowindexdt]'], {}), '([years, snowindexdt])\n', (2939, 2961), True, 'import numpy as np\n')] |
#
# BLAS wrappers
#
from warnings import warn
from info import __doc__
__all__ = ['fblas','cblas','get_blas_funcs']
import fblas
import cblas
from numpy import deprecate
_use_force_cblas = 1
if hasattr(cblas,'empty_module'):
cblas = fblas
_use_force_cblas = 0
elif hasattr(fblas,'empty_module'):
fblas = cblas
_type_conv = {'f':'s', 'd':'d', 'F':'c', 'D':'z'} # 'd' will be default for 'i',..
_inv_type_conv = {'s':'f','d':'d','c':'F','z':'D'}
@deprecate
def get_blas_funcs(names,arrays=(),debug=0):
"""
This function is deprecated, use scipy.linalg.get_blas_funcs instead.
Return available BLAS function objects with names.
arrays are used to determine the optimal prefix of
BLAS routines.
"""
ordering = []
for i in range(len(arrays)):
t = arrays[i].dtype.char
if t not in _type_conv:
t = 'd'
ordering.append((t,i))
if ordering:
ordering.sort()
required_prefix = _type_conv[ordering[0][0]]
else:
required_prefix = 'd'
dtypechar = _inv_type_conv[required_prefix]
# Default lookup:
if ordering and arrays[ordering[0][1]].flags['FORTRAN']:
# prefer Fortran code for leading array with column major order
m1,m2 = fblas,cblas
else:
# in all other cases, C code is preferred
m1,m2 = cblas,fblas
funcs = []
for name in names:
if name=='ger' and dtypechar in 'FD':
name = 'gerc'
elif name in ('dotc', 'dotu') and dtypechar in 'fd':
name = 'dot'
func_name = required_prefix + name
if name == 'nrm2' and dtypechar == 'D':
func_name = 'dznrm2'
elif name == 'nrm2' and dtypechar == 'F':
func_name = 'scnrm2'
func = getattr(m1,func_name,None)
if func is None:
func = getattr(m2,func_name)
func.module_name = m2.__name__.split('.')[-1]
else:
func.module_name = m1.__name__.split('.')[-1]
func.prefix = required_prefix
func.dtypechar = dtypechar
funcs.append(func)
return tuple(funcs)
from numpy.testing import Tester
test = Tester().test
| [
"numpy.testing.Tester"
] | [((2166, 2174), 'numpy.testing.Tester', 'Tester', ([], {}), '()\n', (2172, 2174), False, 'from numpy.testing import Tester\n')] |
import numpy as np
import dataset
import os
btch_sz = 200
lrn_rt = 1e-1
epoch_cnt = 10
class RNN:
def __init__(self, hidden_size, sequence_length, vocab_size):
self.hidden_size = hidden_size
self.sequence_length = sequence_length
self.vocab_size = vocab_size
self.U = np.random.normal(0, 1e-2, (vocab_size, hidden_size)) # ... input projection
self.W = np.random.normal(0, 1e-2, (hidden_size, hidden_size)) # ... hidden-to-hidden projection
self.b = np.zeros((1, hidden_size)) # ... input bias
self.V = np.random.normal(0, 1e-2, (hidden_size, vocab_size)) # ... output projection
self.c = np.zeros((1, vocab_size)) # ... output bias
def step_forward(self, x, h_prev):
# A single time step forward of a recurrent neural network with a
# hyperbolic tangent nonlinearity.
# x - input data (minibatch size x input dimension)
# h_prev - previous hidden state (minibatch size x hidden size)
# U - input projection matrix (input dimension x hidden size)
# W - hidden to hidden projection matrix (hidden size x hidden size)
# b - bias of shape (hidden size x 1)
# return the new hidden state and a tuple of values needed for the backward step
h_current = np.tanh(np.dot(h_prev, self.W) + np.dot(x, self.U) + self.b)
return h_current, (h_prev, x, h_current)
def forward(self, x, h0):
# Full unroll forward of the recurrent neural network with a
# hyperbolic tangent nonlinearity
# x - input data for the whole time-series (minibatch size x sequence_length x input dimension)
# h0 - initial hidden state (minibatch size x hidden size)
# U - input projection matrix (input dimension x hidden size)
# W - hidden to hidden projection matrix (hidden size x hidden size)
# b - bias of shape (hidden size x 1)
h, cache = [], []
h_prev = h0
for i in range(x.shape[1]):
h_i, cache_i = self.step_forward(x[:, i], h_prev)
h.append(h_i)
cache.append(cache_i)
h_prev = h_i
# return the hidden states for the whole time series (T+1) and a tuple of values needed for the backward step
return h, cache
def step_backward(self, grad_next, cache):
# A single time step backward of a recurrent neural network with a
# hyperbolic tangent nonlinearity.
# grad_next - upstream gradient of the loss with respect to the next hidden state and current output
# cache - cached information from the forward pass
dU, dW, db = None, None, None
# compute and return gradients with respect to each parameter
# HINT: you can use the chain rule to compute the derivative of the
# hyperbolic tangent function and use it to compute the gradient
# with respect to the remaining parameters
da = grad_next * (1 - cache[2]**2)
dW = np.dot(cache[0].T, da)
dU = np.dot(cache[1].T, da)
db = da.sum(axis=0)
grad_prev = np.dot(da, self.W.T)
return grad_prev, dU, dW, db
def backward(self, dh, cache):
# Full unroll forward of the recurrent neural network with a
# hyperbolic tangent nonlinearity
dU, dW, db = np.zeros_like(self.U), np.zeros_like(self.W), np.zeros_like(self.b)
# compute and return gradients with respect to each parameter
# for the whole time series.
# Why are we not computing the gradient with respect to inputs (x)?
dh_i = 0
for i in reversed(range(len(dh))):
dh[i] += dh_i
dh_i, dU_i, dW_i, db_i = self.step_backward(dh[i], cache[i])
dU += dU_i
dW += dW_i
db += db_i
return dU, dW, db
def output(self, h):
# Calculate the output probabilities of the network
probs = []
for i in range(len(h)):
probs.append(np.dot(h[i], self.V) + self.c)
return probs
def output_loss_and_grads(self, h, y):
# Calculate the loss of the network for each of the outputs
# h - hidden states of the network for each timestep.
# the dimensionality of h is (batch size x sequence length x hidden size (the initial state is irrelevant for the output)
# V - the output projection matrix of dimension hidden size x vocabulary size
# c - the output bias of dimension vocabulary size x 1
# y - the true class distribution - a tensor of dimension
# batch_size x sequence_length x vocabulary size - you need to do this conversion prior to
# passing the argument. A fast way to create a one-hot vector from
# an id could be something like the following code:
# y[batch_id][timestep] = np.zeros((vocabulary_size, 1))
# y[batch_id][timestep][batch_y[timestep]] = 1
# where y might be a list or a dictionary.
loss, dh, dV, dc = None, [], np.zeros_like(self.V), np.zeros_like(self.c)
# calculate the output (o) - unnormalized log probabilities of classes
# calculate yhat - softmax of the output
# calculate the cross-entropy loss
# calculate the derivative of the cross-entropy softmax loss with respect to the output (o)
# calculate the gradients with respect to the output parameters V and c
# calculate the gradients with respect to the hidden layer h
N = y.shape[0]
logprobs = np.zeros_like(y)
o = self.output(h)
for i in range(len(o)):
# softmax(o)
expscores = np.exp(o[i] - np.max(o[i]))
sumexp = np.sum(expscores, axis=1, keepdims=True)
probs = expscores / sumexp
# log(softmax(o))
logprobs[:, i] = np.log(probs)
# backprop
do = probs - y[:, i]
dV += np.dot(h[i].T, do)
dc += do.sum(axis=0)
dh.append(np.dot(do, self.V.T))
loss = - 1 / N * np.sum(logprobs * y)
return loss, dh, dV, dc
def update(self, dU, dW, dV, db, dc):
self.U += dU
self.W += dW
self.V += dV
self.b += db
self.c += dc
class Adagrad:
def __init__(self, rnn, hidden_size, vocab_size, learning_rate, delta=1e-7):
self.learning_rate = learning_rate
self.delta = delta
self.rnn = rnn
self.memory_U, self.memory_W, self.memory_V = np.zeros((vocab_size, hidden_size)), np.zeros(
(hidden_size, hidden_size)), np.zeros((hidden_size, vocab_size))
self.memory_b, self.memory_c = np.zeros((1, hidden_size)), np.zeros((1, vocab_size))
def step(self, h0, x_oh, y_oh):
h, cache = self.rnn.forward(x_oh, h0)
loss, gh, gV, gc = self.rnn.output_loss_and_grads(h, y_oh)
gU, gW, gb = self.rnn.backward(gh, cache)
N = x_oh.shape[0]
gU /= N
gW /= N
gV /= N
gb /= N
gc /= N
np.clip(gU, -5, 5, out=gU)
np.clip(gW, -5, 5, out=gW)
np.clip(gV, -5, 5, out=gV)
np.clip(gb, -5, 5, out=gb)
np.clip(gc, -5, 5, out=gc)
self.memory_U += gU**2
self.memory_W += gW**2
self.memory_V += gV**2
self.memory_b += gb**2
self.memory_c += gc**2
dU = - (self.learning_rate / (self.delta + np.sqrt(self.memory_U))) * gU
dW = - (self.learning_rate / (self.delta + np.sqrt(self.memory_W))) * gW
dV = - (self.learning_rate / (self.delta + np.sqrt(self.memory_V))) * gV
db = - (self.learning_rate / (self.delta + np.sqrt(self.memory_b))) * gb
dc = - (self.learning_rate / (self.delta + np.sqrt(self.memory_c))) * gc
self.rnn.update(dU, dW, dV, db, dc)
return loss, h[-1]
def to_one_hot(x, vocab_size):
# x_one_hot = np.zeros((x.shape[0], x.shape[1], vocab_size))
#
# for batch_id in range(x.shape[0]):
# for timestep in range(x.shape[1]):
# x_one_hot[batch_id][timestep][x[batch_id][timestep]] = 1
#
# return x_one_hot
return (np.arange(vocab_size) == x[..., None]-1).astype(int)
def sample(dataset, rnn, seed, n_sample, hidden_size, sequence_length, batch_size):
vocab_size = len(dataset.sorted_chars)
h0 = np.zeros((batch_size, hidden_size))
seed_one_hot = to_one_hot(np.expand_dims(dataset.encode(seed), axis=0), vocab_size)
sample = ""
while len(sample) < n_sample:
h0, _ = rnn.forward(seed_one_hot, h0)
o = rnn.output(h0)
for i in range(len(o)):
sample += ''.join(dataset.decode(o[i].argmax(axis=1)))
return sample[len(seed):]
def run_language_model(dataset, max_epochs, hidden_size=100, sequence_length=30, learning_rate=1e-1, sample_every=100, batch_size=196):
vocab_size = len(dataset.sorted_chars)
rnn = RNN(hidden_size, sequence_length, vocab_size) # initialize the recurrent network
optimizer = Adagrad(rnn, hidden_size, vocab_size, learning_rate)
current_epoch = 0
batch = 0
h0 = np.zeros((batch_size, hidden_size))
average_loss = 0
while current_epoch < max_epochs:
e, x, y = dataset.next_minibatch()
if e:
print('Average loss %f0.2' % (average_loss / dataset.num_batches))
print()
current_epoch += 1
average_loss = 0
h0 = np.zeros((batch_size, hidden_size))
# why do we reset the hidden state here?
# One-hot transform the x and y batches
x_oh, y_oh = to_one_hot(x, vocab_size), to_one_hot(y, vocab_size)
# Run the recurrent network on the current batch
# Since we are using windows of a short length of characters,
# the step function should return the hidden state at the end
# of the unroll. You should then use that hidden state as the
# input for the next minibatch. In this way, we artificially
# preserve context between batches.
loss, h0 = optimizer.step(h0, x_oh, y_oh)
average_loss += loss
if batch % sample_every == 0:
s = sample(dataset, rnn, "HAN:\nIs that good or bad?\n\n", 300, hidden_size, sequence_length, batch_size)
print(s)
print('Epoch=%d, batch=%d/%d, loss=%f0.2' % (
current_epoch, (batch % dataset.num_batches) + 1, dataset.num_batches, loss))
batch += 1
if __name__ == '__main__':
np.random.seed(100)
root = 'data'
input_destination = 'selected_conversations.txt'
dataset = dataset.Dataset(btch_sz, 30)
dataset.preprocess(os.path.join(root, input_destination))
dataset.create_minibatches()
run_language_model(dataset, epoch_cnt, batch_size=btch_sz, learning_rate=lrn_rt)
# root = 'data'
# input_destination = 'selected_conversations.txt'
# dataset = dataset.Dataset(500, 30)
# dataset.preprocess(os.path.join(root, input_destination))
# dataset.create_minibatches()
# vocab_size = len(dataset.sorted_chars)
# new_epoch, batch_x, batch_y = dataset.next_minibatch()
# f_x = open("batch_x.txt", "w+")
# f_y = open("batch_y.txt", "w+")
# f_x_one = open("batch_x_one.txt", "w+")
# f_y_one = open("batch_y_one.txt", "w+")
# while not new_epoch:
# x_oh, y_oh = to_one_hot(batch_x, vocab_size), to_one_hot(batch_y, vocab_size)
# for i in range(dataset.num_batches):
# np.savetxt(f_x_one, x_oh[i], '%d', delimiter='')
# np.savetxt(f_y_one, y_oh[i], '%d', delimiter='')
# np.savetxt(f_x, batch_x, '%d')
# np.savetxt(f_y, batch_y, '%d')
# new_epoch, batch_x, batch_y = dataset.next_minibatch()
| [
"numpy.zeros_like",
"numpy.random.seed",
"numpy.sum",
"numpy.log",
"dataset.Dataset",
"dataset.encode",
"numpy.zeros",
"numpy.clip",
"numpy.max",
"numpy.arange",
"dataset.create_minibatches",
"numpy.random.normal",
"dataset.next_minibatch",
"numpy.dot",
"os.path.join",
"numpy.sqrt"
] | [((8358, 8393), 'numpy.zeros', 'np.zeros', (['(batch_size, hidden_size)'], {}), '((batch_size, hidden_size))\n', (8366, 8393), True, 'import numpy as np\n'), ((9124, 9159), 'numpy.zeros', 'np.zeros', (['(batch_size, hidden_size)'], {}), '((batch_size, hidden_size))\n', (9132, 9159), True, 'import numpy as np\n'), ((10501, 10520), 'numpy.random.seed', 'np.random.seed', (['(100)'], {}), '(100)\n', (10515, 10520), True, 'import numpy as np\n'), ((10606, 10634), 'dataset.Dataset', 'dataset.Dataset', (['btch_sz', '(30)'], {}), '(btch_sz, 30)\n', (10621, 10634), False, 'import dataset\n'), ((10701, 10729), 'dataset.create_minibatches', 'dataset.create_minibatches', ([], {}), '()\n', (10727, 10729), False, 'import dataset\n'), ((308, 360), 'numpy.random.normal', 'np.random.normal', (['(0)', '(0.01)', '(vocab_size, hidden_size)'], {}), '(0, 0.01, (vocab_size, hidden_size))\n', (324, 360), True, 'import numpy as np\n'), ((402, 455), 'numpy.random.normal', 'np.random.normal', (['(0)', '(0.01)', '(hidden_size, hidden_size)'], {}), '(0, 0.01, (hidden_size, hidden_size))\n', (418, 455), True, 'import numpy as np\n'), ((508, 534), 'numpy.zeros', 'np.zeros', (['(1, hidden_size)'], {}), '((1, hidden_size))\n', (516, 534), True, 'import numpy as np\n'), ((571, 623), 'numpy.random.normal', 'np.random.normal', (['(0)', '(0.01)', '(hidden_size, vocab_size)'], {}), '(0, 0.01, (hidden_size, vocab_size))\n', (587, 623), True, 'import numpy as np\n'), ((666, 691), 'numpy.zeros', 'np.zeros', (['(1, vocab_size)'], {}), '((1, vocab_size))\n', (674, 691), True, 'import numpy as np\n'), ((3000, 3022), 'numpy.dot', 'np.dot', (['cache[0].T', 'da'], {}), '(cache[0].T, da)\n', (3006, 3022), True, 'import numpy as np\n'), ((3036, 3058), 'numpy.dot', 'np.dot', (['cache[1].T', 'da'], {}), '(cache[1].T, da)\n', (3042, 3058), True, 'import numpy as np\n'), ((3107, 3127), 'numpy.dot', 'np.dot', (['da', 'self.W.T'], {}), '(da, self.W.T)\n', (3113, 3127), True, 'import numpy as np\n'), ((5558, 5574), 'numpy.zeros_like', 'np.zeros_like', (['y'], {}), '(y)\n', (5571, 5574), True, 'import numpy as np\n'), ((7063, 7089), 'numpy.clip', 'np.clip', (['gU', '(-5)', '(5)'], {'out': 'gU'}), '(gU, -5, 5, out=gU)\n', (7070, 7089), True, 'import numpy as np\n'), ((7098, 7124), 'numpy.clip', 'np.clip', (['gW', '(-5)', '(5)'], {'out': 'gW'}), '(gW, -5, 5, out=gW)\n', (7105, 7124), True, 'import numpy as np\n'), ((7133, 7159), 'numpy.clip', 'np.clip', (['gV', '(-5)', '(5)'], {'out': 'gV'}), '(gV, -5, 5, out=gV)\n', (7140, 7159), True, 'import numpy as np\n'), ((7168, 7194), 'numpy.clip', 'np.clip', (['gb', '(-5)', '(5)'], {'out': 'gb'}), '(gb, -5, 5, out=gb)\n', (7175, 7194), True, 'import numpy as np\n'), ((7203, 7229), 'numpy.clip', 'np.clip', (['gc', '(-5)', '(5)'], {'out': 'gc'}), '(gc, -5, 5, out=gc)\n', (7210, 7229), True, 'import numpy as np\n'), ((9239, 9263), 'dataset.next_minibatch', 'dataset.next_minibatch', ([], {}), '()\n', (9261, 9263), False, 'import dataset\n'), ((10658, 10695), 'os.path.join', 'os.path.join', (['root', 'input_destination'], {}), '(root, input_destination)\n', (10670, 10695), False, 'import os\n'), ((3335, 3356), 'numpy.zeros_like', 'np.zeros_like', (['self.U'], {}), '(self.U)\n', (3348, 3356), True, 'import numpy as np\n'), ((3358, 3379), 'numpy.zeros_like', 'np.zeros_like', (['self.W'], {}), '(self.W)\n', (3371, 3379), True, 'import numpy as np\n'), ((3381, 3402), 'numpy.zeros_like', 'np.zeros_like', (['self.b'], {}), '(self.b)\n', (3394, 3402), True, 'import numpy as np\n'), ((5050, 5071), 'numpy.zeros_like', 'np.zeros_like', (['self.V'], {}), '(self.V)\n', (5063, 5071), True, 'import numpy as np\n'), ((5073, 5094), 'numpy.zeros_like', 'np.zeros_like', (['self.c'], {}), '(self.c)\n', (5086, 5094), True, 'import numpy as np\n'), ((5733, 5773), 'numpy.sum', 'np.sum', (['expscores'], {'axis': '(1)', 'keepdims': '(True)'}), '(expscores, axis=1, keepdims=True)\n', (5739, 5773), True, 'import numpy as np\n'), ((5873, 5886), 'numpy.log', 'np.log', (['probs'], {}), '(probs)\n', (5879, 5886), True, 'import numpy as np\n'), ((5962, 5980), 'numpy.dot', 'np.dot', (['h[i].T', 'do'], {}), '(h[i].T, do)\n', (5968, 5980), True, 'import numpy as np\n'), ((6084, 6104), 'numpy.sum', 'np.sum', (['(logprobs * y)'], {}), '(logprobs * y)\n', (6090, 6104), True, 'import numpy as np\n'), ((6532, 6567), 'numpy.zeros', 'np.zeros', (['(vocab_size, hidden_size)'], {}), '((vocab_size, hidden_size))\n', (6540, 6567), True, 'import numpy as np\n'), ((6569, 6605), 'numpy.zeros', 'np.zeros', (['(hidden_size, hidden_size)'], {}), '((hidden_size, hidden_size))\n', (6577, 6605), True, 'import numpy as np\n'), ((6620, 6655), 'numpy.zeros', 'np.zeros', (['(hidden_size, vocab_size)'], {}), '((hidden_size, vocab_size))\n', (6628, 6655), True, 'import numpy as np\n'), ((6695, 6721), 'numpy.zeros', 'np.zeros', (['(1, hidden_size)'], {}), '((1, hidden_size))\n', (6703, 6721), True, 'import numpy as np\n'), ((6723, 6748), 'numpy.zeros', 'np.zeros', (['(1, vocab_size)'], {}), '((1, vocab_size))\n', (6731, 6748), True, 'import numpy as np\n'), ((8439, 8459), 'dataset.encode', 'dataset.encode', (['seed'], {}), '(seed)\n', (8453, 8459), False, 'import dataset\n'), ((9455, 9490), 'numpy.zeros', 'np.zeros', (['(batch_size, hidden_size)'], {}), '((batch_size, hidden_size))\n', (9463, 9490), True, 'import numpy as np\n'), ((6036, 6056), 'numpy.dot', 'np.dot', (['do', 'self.V.T'], {}), '(do, self.V.T)\n', (6042, 6056), True, 'import numpy as np\n'), ((8167, 8188), 'numpy.arange', 'np.arange', (['vocab_size'], {}), '(vocab_size)\n', (8176, 8188), True, 'import numpy as np\n'), ((1313, 1335), 'numpy.dot', 'np.dot', (['h_prev', 'self.W'], {}), '(h_prev, self.W)\n', (1319, 1335), True, 'import numpy as np\n'), ((1338, 1355), 'numpy.dot', 'np.dot', (['x', 'self.U'], {}), '(x, self.U)\n', (1344, 1355), True, 'import numpy as np\n'), ((4008, 4028), 'numpy.dot', 'np.dot', (['h[i]', 'self.V'], {}), '(h[i], self.V)\n', (4014, 4028), True, 'import numpy as np\n'), ((5698, 5710), 'numpy.max', 'np.max', (['o[i]'], {}), '(o[i])\n', (5704, 5710), True, 'import numpy as np\n'), ((7438, 7460), 'numpy.sqrt', 'np.sqrt', (['self.memory_U'], {}), '(self.memory_U)\n', (7445, 7460), True, 'import numpy as np\n'), ((7519, 7541), 'numpy.sqrt', 'np.sqrt', (['self.memory_W'], {}), '(self.memory_W)\n', (7526, 7541), True, 'import numpy as np\n'), ((7600, 7622), 'numpy.sqrt', 'np.sqrt', (['self.memory_V'], {}), '(self.memory_V)\n', (7607, 7622), True, 'import numpy as np\n'), ((7681, 7703), 'numpy.sqrt', 'np.sqrt', (['self.memory_b'], {}), '(self.memory_b)\n', (7688, 7703), True, 'import numpy as np\n'), ((7762, 7784), 'numpy.sqrt', 'np.sqrt', (['self.memory_c'], {}), '(self.memory_c)\n', (7769, 7784), True, 'import numpy as np\n')] |
# Copyright 2022 The jax3d Authors.
#
# 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.
"""Tests for jax3d.projects.nesf.nerfstatic.utils.types."""
import jax.numpy as jnp
from jax3d.projects.nesf.nerfstatic.utils import types
import numpy as np
def test_bounding_box_simple():
bbox = types.BoundingBox3d(
min_corner=jnp.asarray([0, 0, 0]),
max_corner=jnp.asarray([1, 1, 1]))
rays = types.Rays(origin=jnp.asarray([10, 10, 10]),
direction=jnp.asarray([1, 1, 1]),
scene_id=None)
assert bbox.intersect_rays(rays) == (-10, -9)
def test_bounding_box_zero_dir():
bbox = types.BoundingBox3d(
min_corner=jnp.asarray([0, 0, 0]),
max_corner=jnp.asarray([1, 1, 1]))
rays = types.Rays(origin=jnp.asarray([10, 0.5, 0.5]),
direction=jnp.asarray([1, 0, 0]),
scene_id=None)
assert bbox.intersect_rays(rays) == (-10, -9)
def test_bounding_box_no_intersection():
bbox = types.BoundingBox3d(
min_corner=jnp.asarray([0, 0, 0]),
max_corner=jnp.asarray([1, 1, 1]))
rays = types.Rays(origin=jnp.asarray([10, 10, 10]),
direction=jnp.asarray([1, 0, 0]),
scene_id=None)
i = bbox.intersect_rays(rays)
assert i[1] < i[0]
def test_point_cloud():
h, w = 6, 8
normalize = lambda x: x / np.linalg.norm(x, axis=-1, keepdims=True)
rays = types.Rays(scene_id=np.zeros((h, w, 1), dtype=np.int32),
origin=np.random.rand(h, w, 3),
direction=normalize(np.random.randn(h, w, 3)))
views = types.Views(rays=rays,
depth=np.random.rand(h, w, 1),
semantics=np.random.randint(0, 5, size=(h, w, 1)))
# Construct point cloud.
point_cloud = views.point_cloud
# Only valid points.
assert np.all(point_cloud.points >= -1)
assert np.all(point_cloud.points <= 1)
# Size matches expected value.
assert (point_cloud.size ==
point_cloud.points.shape[0] ==
point_cloud.semantics.shape[0])
| [
"numpy.random.randn",
"numpy.zeros",
"jax.numpy.asarray",
"numpy.random.randint",
"numpy.linalg.norm",
"numpy.random.rand",
"numpy.all"
] | [((2323, 2355), 'numpy.all', 'np.all', (['(point_cloud.points >= -1)'], {}), '(point_cloud.points >= -1)\n', (2329, 2355), True, 'import numpy as np\n'), ((2365, 2396), 'numpy.all', 'np.all', (['(point_cloud.points <= 1)'], {}), '(point_cloud.points <= 1)\n', (2371, 2396), True, 'import numpy as np\n'), ((823, 845), 'jax.numpy.asarray', 'jnp.asarray', (['[0, 0, 0]'], {}), '([0, 0, 0])\n', (834, 845), True, 'import jax.numpy as jnp\n'), ((864, 886), 'jax.numpy.asarray', 'jnp.asarray', (['[1, 1, 1]'], {}), '([1, 1, 1])\n', (875, 886), True, 'import jax.numpy as jnp\n'), ((916, 941), 'jax.numpy.asarray', 'jnp.asarray', (['[10, 10, 10]'], {}), '([10, 10, 10])\n', (927, 941), True, 'import jax.numpy as jnp\n'), ((973, 995), 'jax.numpy.asarray', 'jnp.asarray', (['[1, 1, 1]'], {}), '([1, 1, 1])\n', (984, 995), True, 'import jax.numpy as jnp\n'), ((1163, 1185), 'jax.numpy.asarray', 'jnp.asarray', (['[0, 0, 0]'], {}), '([0, 0, 0])\n', (1174, 1185), True, 'import jax.numpy as jnp\n'), ((1204, 1226), 'jax.numpy.asarray', 'jnp.asarray', (['[1, 1, 1]'], {}), '([1, 1, 1])\n', (1215, 1226), True, 'import jax.numpy as jnp\n'), ((1256, 1283), 'jax.numpy.asarray', 'jnp.asarray', (['[10, 0.5, 0.5]'], {}), '([10, 0.5, 0.5])\n', (1267, 1283), True, 'import jax.numpy as jnp\n'), ((1315, 1337), 'jax.numpy.asarray', 'jnp.asarray', (['[1, 0, 0]'], {}), '([1, 0, 0])\n', (1326, 1337), True, 'import jax.numpy as jnp\n'), ((1512, 1534), 'jax.numpy.asarray', 'jnp.asarray', (['[0, 0, 0]'], {}), '([0, 0, 0])\n', (1523, 1534), True, 'import jax.numpy as jnp\n'), ((1553, 1575), 'jax.numpy.asarray', 'jnp.asarray', (['[1, 1, 1]'], {}), '([1, 1, 1])\n', (1564, 1575), True, 'import jax.numpy as jnp\n'), ((1605, 1630), 'jax.numpy.asarray', 'jnp.asarray', (['[10, 10, 10]'], {}), '([10, 10, 10])\n', (1616, 1630), True, 'import jax.numpy as jnp\n'), ((1662, 1684), 'jax.numpy.asarray', 'jnp.asarray', (['[1, 0, 0]'], {}), '([1, 0, 0])\n', (1673, 1684), True, 'import jax.numpy as jnp\n'), ((1842, 1883), 'numpy.linalg.norm', 'np.linalg.norm', (['x'], {'axis': '(-1)', 'keepdims': '(True)'}), '(x, axis=-1, keepdims=True)\n', (1856, 1883), True, 'import numpy as np\n'), ((1913, 1948), 'numpy.zeros', 'np.zeros', (['(h, w, 1)'], {'dtype': 'np.int32'}), '((h, w, 1), dtype=np.int32)\n', (1921, 1948), True, 'import numpy as np\n'), ((1977, 2000), 'numpy.random.rand', 'np.random.rand', (['h', 'w', '(3)'], {}), '(h, w, 3)\n', (1991, 2000), True, 'import numpy as np\n'), ((2130, 2153), 'numpy.random.rand', 'np.random.rand', (['h', 'w', '(1)'], {}), '(h, w, 1)\n', (2144, 2153), True, 'import numpy as np\n'), ((2187, 2226), 'numpy.random.randint', 'np.random.randint', (['(0)', '(5)'], {'size': '(h, w, 1)'}), '(0, 5, size=(h, w, 1))\n', (2204, 2226), True, 'import numpy as np\n'), ((2042, 2066), 'numpy.random.randn', 'np.random.randn', (['h', 'w', '(3)'], {}), '(h, w, 3)\n', (2057, 2066), True, 'import numpy as np\n')] |
# translate_doctopics.py
# This script takes the doctopics file produced by MALLET and turns it
# into a form that is slightly easier to read.
import sys
import numpy as np
outrows = []
ctr = 0
split_files = dict()
with open('20thdoctopics.txt', encoding = 'utf-8') as f:
for line in f:
fields = line.strip().split('\t')
fields[1] = fields[1].replace('file:/projects/ischoolichass/ichass/usesofscale/mallet-2.0.8/../code/asymmetry/twentieth/', '')
fields[1] = fields[1].replace('.txt', '')
if '%7C' in fields[1]:
parts = fields[1].split('%7C')
docid = parts[0]
if docid not in split_files:
split_files[docid] = []
split_files[docid].append(np.array([float(x) for x in fields[2:]]))
if len(parts[1]) > 1:
ctr = ctr + 1
else:
outrows.append(fields[1: ])
print(ctr)
header = "docid\t" + '\t'.join([str(x) for x in range(0, 500)]) + '\n'
with open('20th_doc_topics.tsv', mode = 'w', encoding = 'utf-8') as f:
f.write(header)
for row in outrows:
f.write('\t'.join(row) + '\n')
with open('20th_doc_topics.tsv', mode = 'a', encoding = 'utf-8') as f:
for docid, volparts in split_files.items():
allvols = np.sum(volparts, axis = 0)
normalized = allvols / np.sum(allvols)
f.write(docid + '\t' + '\t'.join([str(x) for x in normalized]) + '\n')
| [
"numpy.sum"
] | [((1280, 1304), 'numpy.sum', 'np.sum', (['volparts'], {'axis': '(0)'}), '(volparts, axis=0)\n', (1286, 1304), True, 'import numpy as np\n'), ((1338, 1353), 'numpy.sum', 'np.sum', (['allvols'], {}), '(allvols)\n', (1344, 1353), True, 'import numpy as np\n')] |
import numpy as np
from sklearn import preprocessing, cross_validation, neighbors
import pandas as pd
import serial
import pickle
lis=[1,2,5,6,9,10,13,14]
lis1=[]
j=0
#ser=serial.Serial("COM9",115200)
df=pd.read_csv('Database90.txt')
#df=df.apply(pd.to_numeric)
data = np.array(df)
np.take(data,np.random.permutation(data.shape[0]),axis=0,out=data);
y=np.array(data[:,0])
X=np.array(np.delete(data, [0], 1))
print(X)
print(y)
#X=np.array(df.drop(['Cellnumber'],1))
#y=np.array(df['Cellnumber'])
X_train,X_test,y_train,y_test=cross_validation.train_test_split(X,y,test_size=0.2)
print(X_train,y_train)
clf=neighbors.KNeighborsClassifier(n_neighbors=9)
clf.fit(X_train,y_train)
data_pickle=open('trainned_data90.pkl','wb')
pickle.dump(clf,data_pickle)
accuracy=clf.score(X_test,y_test)
print(accuracy)
data_pickle.close()
| [
"sklearn.cross_validation.train_test_split",
"pickle.dump",
"pandas.read_csv",
"sklearn.neighbors.KNeighborsClassifier",
"numpy.array",
"numpy.random.permutation",
"numpy.delete"
] | [((204, 233), 'pandas.read_csv', 'pd.read_csv', (['"""Database90.txt"""'], {}), "('Database90.txt')\n", (215, 233), True, 'import pandas as pd\n'), ((270, 282), 'numpy.array', 'np.array', (['df'], {}), '(df)\n', (278, 282), True, 'import numpy as np\n'), ((353, 373), 'numpy.array', 'np.array', (['data[:, 0]'], {}), '(data[:, 0])\n', (361, 373), True, 'import numpy as np\n'), ((528, 582), 'sklearn.cross_validation.train_test_split', 'cross_validation.train_test_split', (['X', 'y'], {'test_size': '(0.2)'}), '(X, y, test_size=0.2)\n', (561, 582), False, 'from sklearn import preprocessing, cross_validation, neighbors\n'), ((608, 653), 'sklearn.neighbors.KNeighborsClassifier', 'neighbors.KNeighborsClassifier', ([], {'n_neighbors': '(9)'}), '(n_neighbors=9)\n', (638, 653), False, 'from sklearn import preprocessing, cross_validation, neighbors\n'), ((724, 753), 'pickle.dump', 'pickle.dump', (['clf', 'data_pickle'], {}), '(clf, data_pickle)\n', (735, 753), False, 'import pickle\n'), ((296, 332), 'numpy.random.permutation', 'np.random.permutation', (['data.shape[0]'], {}), '(data.shape[0])\n', (317, 332), True, 'import numpy as np\n'), ((384, 407), 'numpy.delete', 'np.delete', (['data', '[0]', '(1)'], {}), '(data, [0], 1)\n', (393, 407), True, 'import numpy as np\n')] |
import tensorflow as tf
import numpy as np
import logging
import matplotlib.pyplot as plt
import json
import os
import rnn
from reactions import QuadraticEval, ConstraintQuadraticEval, RealReaction
from logger import get_handlers
from collections import namedtuple
from sklearn.metrics.pairwise import euclidean_distances
import pandas as pd
NUM_DIMENSIONS = 3
logging.basicConfig(level=logging.INFO, handlers=get_handlers())
logger = logging.getLogger()
state_space = pd.read_csv('EtNH3Istateset.csv')
class StepOptimizer:
def __init__(self, cell, func, ndim, nsteps, save_path,ckpt_path, logger, constraints):
self.logger = logger
self.cell = cell
self.func = func
self.ndim = ndim
self.save_path = save_path
self.nsteps = nsteps
self.ckpt_path = ckpt_path
self.constraints = constraints
self.init_state = self.cell.get_initial_state(1, tf.float32)
self.results = self.build_graph()
self.saver = tf.train.Saver(tf.global_variables())
self.next_idx = None
def get_state_shapes(self):
return [(s[0].get_shape().as_list(), s[1].get_shape().as_list())
for s in self.init_state]
def step(self, sess, x, y, state):
feed_dict = {'input_x:0':x, 'input_y:0':y}
for i in range(len(self.init_state)):
feed_dict['state_l{0}_c:0'.format(i)] = state[i][0]
feed_dict['state_l{0}_h:0'.format(i)] = state[i][1]
new_x, new_state = sess.run(self.results, feed_dict=feed_dict)
readable_x = self.func.x_convert(np.squeeze(new_x)).reshape(1, NUM_DIMENSIONS)
distances = euclidean_distances(state_space, readable_x)
distances = list(distances)
min_distance = min(distances)
indx = distances.index(min_distance)
# Set next index for extraction
self.next_idx = indx
new_x = self.func.x_normalize(state_space.loc[indx])
new_x = new_x.reshape(1,3)
return new_x, new_state
def build_graph(self):
x = tf.placeholder(tf.float32, shape=[1, self.ndim], name='input_x')
y = tf.placeholder(tf.float32, shape=[1, 1], name='input_y')
state = []
for i in range(len(self.init_state)):
state.append((tf.placeholder(
tf.float32, shape=self.init_state[i][0].get_shape(),
name='state_l{0}_c'.format(i)),
tf.placeholder(
tf.float32, shape=self.init_state[i][1].get_shape(),
name='state_l{0}_h'.format(i))))
with tf.name_scope('opt_cell'):
new_x, new_state = self.cell(x, y, state)
if self.constraints:
new_x = tf.clip_by_value(new_x, 0.01, 0.99)
return new_x, new_state
def load(self, sess, ckpt_path):
ckpt = tf.train.get_checkpoint_state(ckpt_path)
if ckpt and ckpt.model_checkpoint_path:
logger.info('Reading model parameters from {}.'.format(
ckpt.model_checkpoint_path))
self.saver.restore(sess, ckpt.model_checkpoint_path)
else:
raise FileNotFoundError('No checkpoint available')
def save(self, sess, save_path):
self.saver.save(sess, save_path)
def get_init(self, starting_location):
x = self.func.x_normalize(list(state_space.loc[starting_location]))
x = x.reshape(1,3)
y = np.array(self.func(x)).reshape(1, 1)
init_state = [(np.zeros(s[0]), np.zeros(s[1]))
for s in self.get_state_shapes()]
return x, y, init_state
def run(self, previous_location):
with tf.Session() as sess:
self.load(sess, self.ckpt_path)
x, y, state = self.get_init(previous_location)
x_array = np.zeros((self.nsteps + 1, self.ndim))
y_array = np.zeros((self.nsteps + 1, 1))
x_array[0, :] = x
y_array[0] = y
# for i in range(self.nsteps):
# x, state = self.step(sess, x, y, state)
# y = np.array(self.func(x)).reshape(1, 1)
# x_array[i+1, :] = x
# y_array[i+1] = y
self.save(sess, self.save_path)
return x_array, y_array
def run_current_step(self):
"""
* Using most recent experiment, get next step
* Save across the other steps
"""
pass
def main():
config_file = open('./config.json')
config = json.load(config_file,
object_hook=lambda d:namedtuple('x', d.keys())(*d.values()))
# update number of parameters to all those considred in the data set
param_names = []
param_range = []
for col in state_space:
param_names.append(col)
param_range.append((state_space[col].min(), state_space[col].max()))
func = RealReaction(num_dim = len(param_names), param_range=param_range, param_names=param_names,
direction='max', logger=None)
cell = rnn.StochasticRNNCell(cell=rnn.LSTM,
kwargs={'hidden_size':config.hidden_size},
nlayers=config.num_layers,
reuse=config.reuse)
# Assumes that previous step exists
# e.g. current_step = 2 means that the first step is in place
next_states = []
for baseline_num in range(1, 10):
# print (config.sav)
df = pd.read_csv('./ckpt/baseline/baseline_{}/trace.csv'.format(baseline_num))
l = list(df['step'])
current_step = len(l) + 1
save_path_of_previous_step = "./ckpt/baseline/baseline_{}/step{}".format(baseline_num, current_step - 1)
save_path = './ckpt/baseline/baseline_{}/step{}'.format(baseline_num, current_step)
if not os.path.exists(save_path):
os.makedirs(save_path)
optimizer = StepOptimizer(cell=cell, func=func, ndim=config.num_params,
nsteps=1, save_path=save_path,
ckpt_path=save_path_of_previous_step,logger=logger,
constraints=config.constraints)
print (save_path_of_previous_step)
x_array, y_array = optimizer.run(l[-1])
l.append(optimizer.next_idx)
pd.DataFrame(l).to_csv('./ckpt/baseline/baseline_{}/trace.csv'.format(baseline_num))
next_states.append(optimizer.next_idx)
pritn (next_states)
# plt.figure(1)
# plt.plot(y_array)
# plt.show()
if __name__ == '__main__':
main()
| [
"pandas.DataFrame",
"tensorflow.train.get_checkpoint_state",
"logger.get_handlers",
"os.makedirs",
"tensorflow.clip_by_value",
"pandas.read_csv",
"tensorflow.Session",
"sklearn.metrics.pairwise.euclidean_distances",
"numpy.zeros",
"os.path.exists",
"tensorflow.placeholder",
"tensorflow.global_... | [((440, 459), 'logging.getLogger', 'logging.getLogger', ([], {}), '()\n', (457, 459), False, 'import logging\n'), ((475, 508), 'pandas.read_csv', 'pd.read_csv', (['"""EtNH3Istateset.csv"""'], {}), "('EtNH3Istateset.csv')\n", (486, 508), True, 'import pandas as pd\n'), ((5093, 5225), 'rnn.StochasticRNNCell', 'rnn.StochasticRNNCell', ([], {'cell': 'rnn.LSTM', 'kwargs': "{'hidden_size': config.hidden_size}", 'nlayers': 'config.num_layers', 'reuse': 'config.reuse'}), "(cell=rnn.LSTM, kwargs={'hidden_size': config.\n hidden_size}, nlayers=config.num_layers, reuse=config.reuse)\n", (5114, 5225), False, 'import rnn\n'), ((415, 429), 'logger.get_handlers', 'get_handlers', ([], {}), '()\n', (427, 429), False, 'from logger import get_handlers\n'), ((1659, 1703), 'sklearn.metrics.pairwise.euclidean_distances', 'euclidean_distances', (['state_space', 'readable_x'], {}), '(state_space, readable_x)\n', (1678, 1703), False, 'from sklearn.metrics.pairwise import euclidean_distances\n'), ((2063, 2127), 'tensorflow.placeholder', 'tf.placeholder', (['tf.float32'], {'shape': '[1, self.ndim]', 'name': '"""input_x"""'}), "(tf.float32, shape=[1, self.ndim], name='input_x')\n", (2077, 2127), True, 'import tensorflow as tf\n'), ((2140, 2196), 'tensorflow.placeholder', 'tf.placeholder', (['tf.float32'], {'shape': '[1, 1]', 'name': '"""input_y"""'}), "(tf.float32, shape=[1, 1], name='input_y')\n", (2154, 2196), True, 'import tensorflow as tf\n'), ((2910, 2950), 'tensorflow.train.get_checkpoint_state', 'tf.train.get_checkpoint_state', (['ckpt_path'], {}), '(ckpt_path)\n', (2939, 2950), True, 'import tensorflow as tf\n'), ((1012, 1033), 'tensorflow.global_variables', 'tf.global_variables', ([], {}), '()\n', (1031, 1033), True, 'import tensorflow as tf\n'), ((2651, 2676), 'tensorflow.name_scope', 'tf.name_scope', (['"""opt_cell"""'], {}), "('opt_cell')\n", (2664, 2676), True, 'import tensorflow as tf\n'), ((3729, 3741), 'tensorflow.Session', 'tf.Session', ([], {}), '()\n', (3739, 3741), True, 'import tensorflow as tf\n'), ((3877, 3915), 'numpy.zeros', 'np.zeros', (['(self.nsteps + 1, self.ndim)'], {}), '((self.nsteps + 1, self.ndim))\n', (3885, 3915), True, 'import numpy as np\n'), ((3938, 3968), 'numpy.zeros', 'np.zeros', (['(self.nsteps + 1, 1)'], {}), '((self.nsteps + 1, 1))\n', (3946, 3968), True, 'import numpy as np\n'), ((5884, 5909), 'os.path.exists', 'os.path.exists', (['save_path'], {}), '(save_path)\n', (5898, 5909), False, 'import os\n'), ((5923, 5945), 'os.makedirs', 'os.makedirs', (['save_path'], {}), '(save_path)\n', (5934, 5945), False, 'import os\n'), ((2789, 2824), 'tensorflow.clip_by_value', 'tf.clip_by_value', (['new_x', '(0.01)', '(0.99)'], {}), '(new_x, 0.01, 0.99)\n', (2805, 2824), True, 'import tensorflow as tf\n'), ((3557, 3571), 'numpy.zeros', 'np.zeros', (['s[0]'], {}), '(s[0])\n', (3565, 3571), True, 'import numpy as np\n'), ((3573, 3587), 'numpy.zeros', 'np.zeros', (['s[1]'], {}), '(s[1])\n', (3581, 3587), True, 'import numpy as np\n'), ((6381, 6396), 'pandas.DataFrame', 'pd.DataFrame', (['l'], {}), '(l)\n', (6393, 6396), True, 'import pandas as pd\n'), ((1593, 1610), 'numpy.squeeze', 'np.squeeze', (['new_x'], {}), '(new_x)\n', (1603, 1610), True, 'import numpy as np\n')] |
import numpy as np
import pandas as pd
from sklearn import preprocessing
from sklearn import model_selection
class DataPrep(object):
"""
Data preparation class for pre-processing input data and post-processing generated data
Variables:
1) raw_df -> dataframe containing input data
2) categorical -> list of categorical columns
3) log -> list of skewed exponential numerical columns
4) mixed -> dictionary of "mixed" column names with corresponding categorical modes
5) integer -> list of numeric columns without floating numbers
6) type -> dictionary of problem type (i.e classification/regression) and target column
7) test_ratio -> ratio of size of test to train dataset
Methods:
1) __init__() -> instantiates DataPrep object and handles the pre-processing steps for feeding it to the training algorithm
2) inverse_prep() -> deals with post-processing of the generated data to have the same format as the original dataset
"""
def __init__(self, raw_df: pd.DataFrame, categorical: list, log:list, mixed:dict, integer:list, type:dict, test_ratio:float):
self.categorical_columns = categorical
self.log_columns = log
self.mixed_columns = mixed
self.integer_columns = integer
self.column_types = dict()
self.column_types["categorical"] = []
self.column_types["mixed"] = {}
self.lower_bounds = {}
self.label_encoder_list = []
# Spliting the input data to obtain training dataset
target_col = list(type.values())[0]
y_real = raw_df[target_col]
X_real = raw_df.drop(columns=[target_col])
X_train_real, _, y_train_real, _ = model_selection.train_test_split(X_real ,y_real, test_size=test_ratio, stratify=y_real,random_state=42)
X_train_real[target_col]= y_train_real
# Replacing empty strings with na if any and replace na with empty
self.df = X_train_real
self.df = self.df.replace(r' ', np.nan)
self.df = self.df.fillna('empty')
# Dealing with empty values in numeric columns by replacing it with -9999999 and treating it as categorical mode
all_columns= set(self.df.columns)
irrelevant_missing_columns = set(self.categorical_columns)
relevant_missing_columns = list(all_columns - irrelevant_missing_columns)
for i in relevant_missing_columns:
if i in list(self.mixed_columns.keys()):
if "empty" in list(self.df[i].values):
self.df[i] = self.df[i].apply(lambda x: -9999999 if x=="empty" else x )
self.mixed_columns[i].append(-9999999)
else:
if "empty" in list(self.df[i].values):
self.df[i] = self.df[i].apply(lambda x: -9999999 if x=="empty" else x)
self.mixed_columns[i] = [-9999999]
# Dealing with skewed exponential numeric distributions by applying log transformation
if self.log_columns:
for log_column in self.log_columns:
# Value added to apply log to non-positive numeric values
eps = 1
# Missing values indicated with -9999999 are skipped
lower = np.min(self.df.loc[self.df[log_column]!=-9999999][log_column].values)
self.lower_bounds[log_column] = lower
if lower>0:
self.df[log_column] = self.df[log_column].apply(lambda x: np.log(x) if x!=-9999999 else -9999999)
elif lower == 0:
self.df[log_column] = self.df[log_column].apply(lambda x: np.log(x+eps) if x!=-9999999 else -9999999)
else:
# Negative values are scaled to become positive to apply log
self.df[log_column] = self.df[log_column].apply(lambda x: np.log(x-lower+eps) if x!=-9999999 else -9999999)
# Encoding categorical column using label encoding to assign each category within a column with an integer value
for column_index, column in enumerate(self.df.columns):
if column in self.categorical_columns:
label_encoder = preprocessing.LabelEncoder()
self.df[column] = self.df[column].astype(str)
label_encoder.fit(self.df[column])
current_label_encoder = dict()
current_label_encoder['column'] = column
current_label_encoder['label_encoder'] = label_encoder
transformed_column = label_encoder.transform(self.df[column])
self.df[column] = transformed_column
self.label_encoder_list.append(current_label_encoder)
self.column_types["categorical"].append(column_index)
elif column in self.mixed_columns:
self.column_types["mixed"][column_index] = self.mixed_columns[column]
super().__init__()
def inverse_prep(self, data, eps=1):
# Converting generated data into a dataframe and assign column names as per original dataset
df_sample = pd.DataFrame(data,columns=self.df.columns)
# Reversing the label encoding assigned to categorical columns according to the original dataset
for i in range(len(self.label_encoder_list)):
le = self.label_encoder_list[i]["label_encoder"]
df_sample[self.label_encoder_list[i]["column"]] = df_sample[self.label_encoder_list[i]["column"]].astype(int)
df_sample[self.label_encoder_list[i]["column"]] = le.inverse_transform(df_sample[self.label_encoder_list[i]["column"]])
# Reversing log by applying exponential transformation with appropriate scaling for non-positive numeric columns
# -9999999 used to denote missing values are similarly ignored
if self.log_columns:
for i in df_sample:
if i in self.log_columns:
lower_bound = self.lower_bounds[i]
if lower_bound>0:
df_sample[i].apply(lambda x: np.exp(x) if x!=-9999999 else -9999999)
elif lower_bound==0:
df_sample[i] = df_sample[i].apply(lambda x: np.ceil(np.exp(x)-eps) if ((x!=-9999999) & ((np.exp(x)-eps) < 0)) else (np.exp(x)-eps if x!=-9999999 else -9999999))
else:
df_sample[i] = df_sample[i].apply(lambda x: np.exp(x)-eps+lower_bound if x!=-9999999 else -9999999)
# Rounding numeric columns without floating numbers in the original dataset
if self.integer_columns:
for column in self.integer_columns:
df_sample[column]= (np.round(df_sample[column].values))
df_sample[column] = df_sample[column].astype(int)
# Converting back -9999999 and "empty" to na
df_sample.replace(-9999999, np.nan,inplace=True)
df_sample.replace('empty', np.nan,inplace=True)
return df_sample
| [
"pandas.DataFrame",
"numpy.log",
"sklearn.model_selection.train_test_split",
"sklearn.preprocessing.LabelEncoder",
"numpy.min",
"numpy.exp",
"numpy.round"
] | [((1714, 1822), 'sklearn.model_selection.train_test_split', 'model_selection.train_test_split', (['X_real', 'y_real'], {'test_size': 'test_ratio', 'stratify': 'y_real', 'random_state': '(42)'}), '(X_real, y_real, test_size=test_ratio,\n stratify=y_real, random_state=42)\n', (1746, 1822), False, 'from sklearn import model_selection\n'), ((5205, 5248), 'pandas.DataFrame', 'pd.DataFrame', (['data'], {'columns': 'self.df.columns'}), '(data, columns=self.df.columns)\n', (5217, 5248), True, 'import pandas as pd\n'), ((3298, 3369), 'numpy.min', 'np.min', (['self.df.loc[self.df[log_column] != -9999999][log_column].values'], {}), '(self.df.loc[self.df[log_column] != -9999999][log_column].values)\n', (3304, 3369), True, 'import numpy as np\n'), ((4255, 4283), 'sklearn.preprocessing.LabelEncoder', 'preprocessing.LabelEncoder', ([], {}), '()\n', (4281, 4283), False, 'from sklearn import preprocessing\n'), ((6803, 6837), 'numpy.round', 'np.round', (['df_sample[column].values'], {}), '(df_sample[column].values)\n', (6811, 6837), True, 'import numpy as np\n'), ((3530, 3539), 'numpy.log', 'np.log', (['x'], {}), '(x)\n', (3536, 3539), True, 'import numpy as np\n'), ((3681, 3696), 'numpy.log', 'np.log', (['(x + eps)'], {}), '(x + eps)\n', (3687, 3696), True, 'import numpy as np\n'), ((3907, 3930), 'numpy.log', 'np.log', (['(x - lower + eps)'], {}), '(x - lower + eps)\n', (3913, 3930), True, 'import numpy as np\n'), ((6175, 6184), 'numpy.exp', 'np.exp', (['x'], {}), '(x)\n', (6181, 6184), True, 'import numpy as np\n'), ((6333, 6342), 'numpy.exp', 'np.exp', (['x'], {}), '(x)\n', (6339, 6342), True, 'import numpy as np\n'), ((6397, 6406), 'numpy.exp', 'np.exp', (['x'], {}), '(x)\n', (6403, 6406), True, 'import numpy as np\n'), ((6537, 6546), 'numpy.exp', 'np.exp', (['x'], {}), '(x)\n', (6543, 6546), True, 'import numpy as np\n'), ((6370, 6379), 'numpy.exp', 'np.exp', (['x'], {}), '(x)\n', (6376, 6379), True, 'import numpy as np\n')] |
#import necessary libraries
import numpy as np
from scipy.sparse import csr_matrix
import sys
sys.path.append("/users/rohan/news-classification/ranking-featured-writing/bert-approach")
import pandas as pd
import torch
import collections
import numpy as np
import os
import argparse
from data_processing.articles import Articles
from models.models import InnerProduct
import data_processing.dictionaries as dictionary
from pathlib import Path
import json
from scipy import sparse
import argparse
from transformers import BertTokenizer
def str2bool(v):
if v.lower() in ('yes', 'true', 't', 'y', '1'):
return True
elif v.lower() in ('no', 'false', 'f', 'n', '0'):
return False
else:
raise argparse.ArgumentTypeError('Boolean value expected.')
def expand_path(string):
return Path(os.path.expandvars(string))
# create and parse necessary arguments
parser = argparse.ArgumentParser(description='Train model on article data and test evaluation')
parser.add_argument('--dict_dir',
type=expand_path,
required=True,
help="This is required to load dictionaries")
parser.add_argument('--data_output_dir',
type=expand_path,
required=True,
help="Location to save mapped and filtered data.")
parser.add_argument('--matrix_output_dir',
type=expand_path,
required=True,
help="Location to save article word sparse matrix.")
parser.add_argument("--dataset_name",
type=str,
required=True,
help="Indicates which dataset for demo this is.")
parser.add_argument("--map_items",
type=str2bool,
required=True,
help="Determine if dataset need to be tokenized, mapped, and filtered.")
parser.add_argument('--data_path',
type=expand_path,
required=True,
help="Location to actual json data.")
args = parser.parse_args()
data_path = Path(args.data_path)
#tokenize, map, and filter data
if args.map_items:
# initialize tokenizer from BERT library
tokenizer = BertTokenizer.from_pretrained('bert-base-uncased', do_lower_case=True)
print("Tokenizer Initialized!")
# dictionaries
dict_dir = Path(args.dict_dir)
final_word_ids,final_url_ids, final_publication_ids = dictionary.load_dictionaries(dict_dir)
print("Dictionaries loaded.")
dataset = Articles(data_path)
print("Data loaded.")
dataset.tokenize(tokenizer)
proper_data = dataset.map_items(tokenizer,
final_url_ids,
final_publication_ids,
filter=True,
min_length=200)
# save mapped data for easier access next iteration
data_path = Path(args.data_output_dir)
if not data_path.is_dir():
data_path.mkdir()
mapped_data_path = data_path / "mapped-data"
if not mapped_data_path.is_dir():
mapped_data_path.mkdir()
train_mapped_path = mapped_data_path / "mapped_dataset_" + args.dataset_name + ".json"
with open(train_mapped_path, "w") as file:
json.dump(proper_data, file)
raw_data = Articles(train_mapped_path)
print("Final: ", len(raw_data))
print(f"Filtered, Mapped Data saved to {mapped_data_path} directory")
print("-------------------")
else:
raw_data = Articles(data_path)
# generate sparse matrix with word ids for each article
rows = []
cols = []
for idx, item in enumerate(raw_data.examples):
word_ids = list(set(item['text']))
number_of_words = np.arange(len(word_ids))
rows.append(np.array(np.ones_like(number_of_words) * idx))
cols.append(np.array(word_ids, dtype=np.int32))
final_rows = np.concatenate(rows, axis=None)
final_cols = np.concatenate(cols, axis=None)
final_data = np.ones_like(final_cols)
word_articles = csr_matrix((final_data, (final_rows, final_cols)))
print("Article Matrix Created!")
matrix_path = args.output_dir + "csr_articles_" + args.dataset_name + ".json"
scipy.sparse.save_npz(matrix_path, csr_matrix(word_articles))
print("Article-Word Matrix Saved") | [
"sys.path.append",
"json.dump",
"numpy.ones_like",
"argparse.ArgumentParser",
"data_processing.articles.Articles",
"os.path.expandvars",
"pathlib.Path",
"scipy.sparse.csr_matrix",
"transformers.BertTokenizer.from_pretrained",
"numpy.array",
"data_processing.dictionaries.load_dictionaries",
"nu... | [((94, 189), 'sys.path.append', 'sys.path.append', (['"""/users/rohan/news-classification/ranking-featured-writing/bert-approach"""'], {}), "(\n '/users/rohan/news-classification/ranking-featured-writing/bert-approach')\n", (109, 189), False, 'import sys\n'), ((896, 987), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""Train model on article data and test evaluation"""'}), "(description=\n 'Train model on article data and test evaluation')\n", (919, 987), False, 'import argparse\n'), ((2117, 2137), 'pathlib.Path', 'Path', (['args.data_path'], {}), '(args.data_path)\n', (2121, 2137), False, 'from pathlib import Path\n'), ((3891, 3922), 'numpy.concatenate', 'np.concatenate', (['rows'], {'axis': 'None'}), '(rows, axis=None)\n', (3905, 3922), True, 'import numpy as np\n'), ((3936, 3967), 'numpy.concatenate', 'np.concatenate', (['cols'], {'axis': 'None'}), '(cols, axis=None)\n', (3950, 3967), True, 'import numpy as np\n'), ((3981, 4005), 'numpy.ones_like', 'np.ones_like', (['final_cols'], {}), '(final_cols)\n', (3993, 4005), True, 'import numpy as np\n'), ((4023, 4073), 'scipy.sparse.csr_matrix', 'csr_matrix', (['(final_data, (final_rows, final_cols))'], {}), '((final_data, (final_rows, final_cols)))\n', (4033, 4073), False, 'from scipy.sparse import csr_matrix\n'), ((2256, 2326), 'transformers.BertTokenizer.from_pretrained', 'BertTokenizer.from_pretrained', (['"""bert-base-uncased"""'], {'do_lower_case': '(True)'}), "('bert-base-uncased', do_lower_case=True)\n", (2285, 2326), False, 'from transformers import BertTokenizer\n'), ((2402, 2421), 'pathlib.Path', 'Path', (['args.dict_dir'], {}), '(args.dict_dir)\n', (2406, 2421), False, 'from pathlib import Path\n'), ((2480, 2518), 'data_processing.dictionaries.load_dictionaries', 'dictionary.load_dictionaries', (['dict_dir'], {}), '(dict_dir)\n', (2508, 2518), True, 'import data_processing.dictionaries as dictionary\n'), ((2576, 2595), 'data_processing.articles.Articles', 'Articles', (['data_path'], {}), '(data_path)\n', (2584, 2595), False, 'from data_processing.articles import Articles\n'), ((2937, 2963), 'pathlib.Path', 'Path', (['args.data_output_dir'], {}), '(args.data_output_dir)\n', (2941, 2963), False, 'from pathlib import Path\n'), ((3331, 3358), 'data_processing.articles.Articles', 'Articles', (['train_mapped_path'], {}), '(train_mapped_path)\n', (3339, 3358), False, 'from data_processing.articles import Articles\n'), ((3524, 3543), 'data_processing.articles.Articles', 'Articles', (['data_path'], {}), '(data_path)\n', (3532, 3543), False, 'from data_processing.articles import Articles\n'), ((4221, 4246), 'scipy.sparse.csr_matrix', 'csr_matrix', (['word_articles'], {}), '(word_articles)\n', (4231, 4246), False, 'from scipy.sparse import csr_matrix\n'), ((819, 845), 'os.path.expandvars', 'os.path.expandvars', (['string'], {}), '(string)\n', (837, 845), False, 'import os\n'), ((3287, 3315), 'json.dump', 'json.dump', (['proper_data', 'file'], {}), '(proper_data, file)\n', (3296, 3315), False, 'import json\n'), ((3837, 3871), 'numpy.array', 'np.array', (['word_ids'], {'dtype': 'np.int32'}), '(word_ids, dtype=np.int32)\n', (3845, 3871), True, 'import numpy as np\n'), ((723, 776), 'argparse.ArgumentTypeError', 'argparse.ArgumentTypeError', (['"""Boolean value expected."""'], {}), "('Boolean value expected.')\n", (749, 776), False, 'import argparse\n'), ((3783, 3812), 'numpy.ones_like', 'np.ones_like', (['number_of_words'], {}), '(number_of_words)\n', (3795, 3812), True, 'import numpy as np\n')] |
from __future__ import (
division,
absolute_import,
with_statement,
print_function,
unicode_literals,
)
import torch
import torch.optim as optim
import torch.nn as nn
from torch.autograd import Variable,Function
from torch.utils.data import DataLoader
from torchvision import transforms
import etw_pytorch_utils as pt_utils
import os.path as osp
import os
import argparse
from pointnet2.models import Pointnet2FaceClsSSG as Pointnet
from pointnet2.data import TripletFaceDataset
import pointnet2.data.data_utils as d_utils
import time
import shutil
from pointnet2.train import layer
import numpy as np
import struct
from sklearn import metrics
torch.backends.cudnn.enabled = True
torch.backends.cudnn.benchmark = True
def parse_args():
parser = argparse.ArgumentParser(
description="Arguments for cls training",
formatter_class=argparse.ArgumentDefaultsHelpFormatter,
)
parser.add_argument("-batch_size", type=int, default=8, help="Batch size")
parser.add_argument(
"-num_points", type=int, default=20000, help="Number of points to train with"
)
parser.add_argument(
"-weight_decay", type=float, default=1e-5, help="L2 regularization coeff"
)
parser.add_argument("-lr", type=float, default=1e-3, help="Initial learning rate")
parser.add_argument(
"-lr_decay", type=float, default=0.7, help="Learning rate decay gamma"
)
parser.add_argument(
"-decay_step", type=float, default=5e3, help="Learning rate decay step"
)
parser.add_argument(
"-bn_momentum", type=float, default=0.5, help="Initial batch norm momentum"
)
parser.add_argument(
"-bnm_decay", type=float, default=0.5, help="Batch norm momentum decay gamma"
)
parser.add_argument(
"-model_checkpoint", type=str, default=None, help="Checkpoint to start from"
)
parser.add_argument(
"-cls_checkpoint", type=str, default=None, help="Checkpoint to start from"
)
parser.add_argument(
"-epochs", type=int, default=30, help="Number of epochs to train for"
)
parser.add_argument(
"-run_name",
type=str,
default="cls_run_1",
help="Name for run in tensorboard_logger",
)
# loss Classifier
parser.add_argument('--margin', type=float, default=0.4, metavar='MARGIN',
help='the margin value for the triplet loss function (default: 1.0')
parser.add_argument('--num_triplet', type=int, default=10000, metavar='num_triplet',
help='the margin value for the triplet loss function (default: 1e4')
parser.add_argument('--num_class', type=int, default=500,
help='number of people(class)')
parser.add_argument('--classifier_type', type=str, default='AL',
help='Which classifier for train. (MCP, AL, L)')
return parser.parse_args()
lr = 1e-3
#lr_clip = 1e-5
#bnm_clip = 1e-2
log_file = './log/triplet_log.txt'
class CosineDistance(Function):
def __init__(self, p):
super(CosineDistance, self).__init__()
self.norm = p
def forward(self, x1, x2):
assert x1.size() == x2.size()
x1_norm = torch.norm(x1,2,1)
x2_norm = torch.norm(x2,2,1)
cos_theta = torch.sum(torch.mul(x1,x2),dim=1) / x1_norm / x2_norm
# print(cos_theta)
cos_theta = cos_theta.clamp(-1, 1) - 1
return -cos_theta
class PairwiseDistance(Function):
def __init__(self, p):
super(PairwiseDistance, self).__init__()
self.norm = p
def forward(self, x1, x2):
assert x1.size() == x2.size()
eps = 1e-4 / x1.size(1)
diff = torch.abs(x1 - x2)
out = torch.pow(diff, self.norm).sum(dim=1)
return torch.pow(out + eps, 1. / self.norm)
l2_dist = CosineDistance(2)
class TripletMarginLoss(Function):
"""Triplet loss function.
"""
def __init__(self, margin):
super(TripletMarginLoss, self).__init__()
self.margin = margin
self.pdist = CosineDistance(2) # norm 2
def forward(self, anchor, positive, negative):
d_p = self.pdist.forward(anchor, positive)
d_n = self.pdist.forward(anchor, negative)
# print(d_p)
# print(d_n)
dist_hinge = torch.clamp(self.margin + d_p - d_n, min=0.0)
loss = torch.mean(dist_hinge)
return loss
class AverageMeter(object):
"""Computes and stores the average and current value"""
def __init__(self):
self.reset()
def reset(self):
self.val = 0
self.avg = 0
self.sum = 0
self.count = 0
def update(self, val, n=1):
self.val = val
self.sum += val * n
self.count += n
self.avg = self.sum / self.count
def adjust_learning_rate(optimizer, epoch):
if epoch in [int(args.epochs*0.3), int(args.epochs*0.6), int(args.epochs*0.9)]:
for param_group in optimizer.param_groups:
param_group['lr'] *= 0.1
def train(train_loader, model, classifier, criterion, optimizer, epoch):
batch_time = AverageMeter()
data_time = AverageMeter()
losses = AverageMeter()
model.train()
end = time.time()
for i, (data_a, data_p, data_n,label_p,label_n) in enumerate(train_loader):
data_time.update(time.time() - end)
# compute output
data_a, data_p, data_n = data_a.cuda(), data_p.cuda(), data_n.cuda()
data_a, data_p, data_n = Variable(data_a,requires_grad=True), Variable(data_p,requires_grad=True), Variable(data_n,requires_grad=True)
# compute output
out_a, out_p, out_n = model(data_a), model(data_p), model(data_n)
# print(out_a.shape)
# Choose the hard negatives
d_p = l2_dist.forward(out_a, out_p)
d_n = l2_dist.forward(out_a, out_n)
# print(d_p)
# print(d_n)
all = (d_n - d_p < args.margin).cpu().data.numpy().flatten()
hard_triplets = np.where(all == 1)
if len(hard_triplets[0]) == 0:
continue
# print(d_p)
out_selected_a = out_a[hard_triplets]
# print(out_selected_a.shape)
out_selected_p = out_p[hard_triplets]
out_selected_n = out_n[hard_triplets]
triplet_loss = TripletMarginLoss(args.margin).forward(out_selected_a, out_selected_p, out_selected_n)
# print(triplet_loss)
loss = triplet_loss
losses.update(loss.item(), data_a.size(0))
# compute gradient and do SGD step
optimizer.zero_grad()
loss.backward()
optimizer.step()
# measure elapsed time
batch_time.update(time.time() - end)
end = time.time()
if i % args.print_freq == 0:
print('Epoch: [{0}][{1}/{2}]\t'
'Time {batch_time.val:.3f} ({batch_time.avg:.3f})\t'
'Data {data_time.val:.3f} ({data_time.avg:.3f})\t'
'Loss {loss.val:.4f} ({loss.avg:.4f})\t'.format(
epoch, i, len(train_loader), batch_time=batch_time,
data_time=data_time, loss=losses))
f.writelines('Epoch: [{0}][{1}/{2}]\t'
'Time {batch_time.val:.3f} ({batch_time.avg:.3f})\t'
'Data {data_time.val:.3f} ({data_time.avg:.3f})\t'
'Loss {loss.val:.4f} ({loss.avg:.4f})\t'.format(
epoch, i, len(train_loader), batch_time=batch_time,
data_time=data_time, loss=losses))
def loadBCNFile(path):
n = os.path.getsize(path) // 4
with open(path, 'rb') as f:
data_raw = struct.unpack('f' * n, f.read(n * 4))
data = np.asarray(data_raw, dtype=np.float32).reshape((4 + 3), n // (4 + 3))
point_set = data.T
# normlize
point_set[:,0:3] = (point_set[:,0:3])/(100)
point_set = torch.from_numpy(point_set)
point_set[:,6] = torch.pow(point_set[:,6],0.1)
return point_set
def validate(model, gfile_list, pfile_list, Label):
model.eval()
optimizer.zero_grad()
# switch to evaluate mode
g_feature = torch.zeros((len(gfile_list), 1, 512))
p_feature = torch.zeros((len(pfile_list), 1, 512))
with torch.set_grad_enabled(False):
for i, file in enumerate(gfile_list):
fname = file
input = loadBCNFile(fname)
input = input.unsqueeze(0).contiguous()
input = input.to("cuda", non_blocking=True)
feat = model(input)# 1x512
g_feature[i, :, :] = feat.cpu()# 105x1x512
# g_label[i] = gclass_list[i]
for i, file in enumerate(pfile_list):
fname = file
input = loadBCNFile(fname)
input = input.unsqueeze(0).contiguous()
input = input.to("cuda", non_blocking=True)
feat = model(input)
p_feature[i, :, :] = feat.cpu()# 194x1x512
# p_label[i] = pclass_list[i]
g_feature2 = torch.norm(g_feature,p=2,dim=2)
p_feature2 = torch.norm(p_feature,p=2,dim=2)
dis = torch.sum(torch.mul(g_feature, p_feature.transpose(1,0)), dim=2) / g_feature2 / p_feature2.transpose(1,0)
top1 = np.equal(torch.argmax(dis,dim=0).numpy(), np.argmax(Label,axis=0)).sum() / len(pfile_list)
print('\nBourphous set: top1: ({})\n'.format(top1))
f.writelines('\nBourphous set: top1: ({})\n'.format(top1))
score = dis.view(-1).numpy()
label = np.reshape(Label,(-1))
fpr, tpr, thresholds = metrics.roc_curve(label, score, pos_label=1)
auc = metrics.auc(fpr, tpr)
print('Bourphous set: auc: ({})\n'.format(auc))
f.writelines('\nBourphous set: auc: ({})\n'.format(auc))
for i in range(len(fpr)):
if fpr[i] >= 1e-3:
# i = i - 1
break
print('Bourphous tpr:{:.4f} @fpr{:.4f}\n'.format(tpr[i],fpr[i]))
f.writelines('\nBourphous tpr:{:.4f} @fpr{:.4f}'.format(tpr[i],fpr[i]))
return top1
def checkpoint_state(model=None,
optimizer=None,
best_prec=None,
epoch=None,
it=None):
optim_state = optimizer.state_dict() if optimizer is not None else None
if model is not None:
if isinstance(model, torch.nn.DataParallel):
model_state = model.module.state_dict()
else:
model_state = model.state_dict()
else:
model_state = None
return {
'epoch': epoch,
'it': it,
'best_prec': best_prec,
'model_state': model_state,
'optimizer_state': optim_state
}
def save_checkpoint(state,
is_best,
filename='checkpoint',
bestname='model_best'):
filename = '{}.pth.tar'.format(filename)
torch.save(state, filename)
if is_best:
shutil.copyfile(filename, '{}.pth.tar'.format(bestname))
def get_list(folder):
pt_list = []
class_list = []
gallery_classes = sorted(os.listdir(folder))
for cname in gallery_classes:
cpath = os.path.join(folder, cname)
gallery = os.listdir(cpath)
for gname in gallery:
gpath = os.path.join(cpath, gname)
pt_list.append(gpath)
class_list.append(cname)
return pt_list, class_list
if __name__ == "__main__":
args = parse_args()
f = open(log_file, 'w')
transforms = transforms.Compose(
[
d_utils.PointcloudRotate(axis=np.array([1, 0, 0])),
d_utils.PointcloudRotate(axis=np.array([0, 1, 0])),
d_utils.PointcloudRotate(axis=np.array([0, 0, 1])),
d_utils.PointcloudJitter(std=0.002),
]
)
train_dataset = TripletFaceDataset(root = '',
n_triplets = args.num_triplet,
n_points = args.num_points,
class_nums = 500,
transforms=None,
extensions='bcnc')
train_loader = DataLoader(
train_dataset,
batch_size=args.batch_size,
shuffle=True,
num_workers=4,
pin_memory=True,
)
model = Pointnet(input_channels=3, use_xyz=True)
model.cuda()
# 512 is dimension of feature
classifier = {
'MCP': layer.MarginCosineProduct(512, args.num_class).cuda(),
'AL' : layer.AngleLinear(512, args.num_class).cuda(),
'L' : torch.nn.Linear(512, args.num_class, bias=False).cuda()
}[args.classifier_type]
criterion = nn.TripletMarginLoss(margin=0.5, p=2)
optimizer = optim.Adam(
[{'params': model.parameters()}, {'params': classifier.parameters()}],
lr=lr, weight_decay=args.weight_decay
)
# default value
it = -1 # for the initialize value of `LambdaLR` and `BNMomentumScheduler`
best_prec1 = 0
best_auc1 = 0
start_epoch = 1
# load status from checkpoint
if args.model_checkpoint is not None:
checkpoint_status = pt_utils.load_checkpoint(
model, optimizer, filename=args.model_checkpoint.split(".")[0]
)
if checkpoint_status is not None:
it, start_epoch, best_loss = checkpoint_status
if args.cls_checkpoint is not None:
checkpoint_status = pt_utils.load_checkpoint(
classifier, optimizer, filename=args.cls_checkpoint.split(".")[0]
)
if checkpoint_status is not None:
it, start_epoch, best_loss = checkpoint_status
for param_group in optimizer.param_groups:
param_group['lr'] = 1e-4
it = max(it, 0) # for the initialize value of `trainer.train`
if not osp.isdir("checkpoints"):
os.makedirs("checkpoints")
## rewrite the training process
checkpoint_name="checkpoints/pointnet2_model"
best_name="checkpoints/pointnet2_model_best"
cls_checkpoint_name="checkpoints/pointnet2_cls"
cls_best_name="checkpoints/pointnet2_cls_best"
eval_frequency = len(train_loader)
eval_gallary_floder = ''
eval_probe_floder = ''
egfile_list, egclass_list= get_list(eval_gallary_floder)
epfile_list, epclass_list= get_list(eval_probe_floder)
elabel = np.zeros((len(egclass_list),len(epclass_list)))
for i, gclass in enumerate(egclass_list):
for j, eclass in enumerate(epclass_list):
if gclass == eclass:
elabel[i,j] = 1
else:
elabel[i,j] = -1
for epoch in range(args.epochs):
#lr_f.write()
adjust_learning_rate(optimizer, epoch)
# train for one epoch
train(train_loader, model, classifier, criterion, optimizer, epoch)
# evaluate on validation set
auc1 = validate(model, egfile_list, epfile_list, elabel)
# save the learned parameters
is_best = auc1 > best_auc1
best_auc1 = max(best_auc1, auc1)
save_checkpoint(
checkpoint_state(model, optimizer,
auc1, args.epochs, epoch),
is_best,
filename=checkpoint_name,
bestname=best_name)
## rewrite the training process end
f.close()
| [
"argparse.ArgumentParser",
"numpy.argmax",
"torch.argmax",
"pointnet2.models.Pointnet2FaceClsSSG",
"pointnet2.train.layer.MarginCosineProduct",
"os.path.join",
"pointnet2.data.data_utils.PointcloudJitter",
"torch.utils.data.DataLoader",
"numpy.reshape",
"torch.nn.Linear",
"torch.nn.TripletMargin... | [((775, 900), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""Arguments for cls training"""', 'formatter_class': 'argparse.ArgumentDefaultsHelpFormatter'}), "(description='Arguments for cls training',\n formatter_class=argparse.ArgumentDefaultsHelpFormatter)\n", (798, 900), False, 'import argparse\n'), ((5235, 5246), 'time.time', 'time.time', ([], {}), '()\n', (5244, 5246), False, 'import time\n'), ((7907, 7934), 'torch.from_numpy', 'torch.from_numpy', (['point_set'], {}), '(point_set)\n', (7923, 7934), False, 'import torch\n'), ((7956, 7987), 'torch.pow', 'torch.pow', (['point_set[:, 6]', '(0.1)'], {}), '(point_set[:, 6], 0.1)\n', (7965, 7987), False, 'import torch\n'), ((9018, 9051), 'torch.norm', 'torch.norm', (['g_feature'], {'p': '(2)', 'dim': '(2)'}), '(g_feature, p=2, dim=2)\n', (9028, 9051), False, 'import torch\n'), ((9067, 9100), 'torch.norm', 'torch.norm', (['p_feature'], {'p': '(2)', 'dim': '(2)'}), '(p_feature, p=2, dim=2)\n', (9077, 9100), False, 'import torch\n'), ((9491, 9512), 'numpy.reshape', 'np.reshape', (['Label', '(-1)'], {}), '(Label, -1)\n', (9501, 9512), True, 'import numpy as np\n'), ((9541, 9585), 'sklearn.metrics.roc_curve', 'metrics.roc_curve', (['label', 'score'], {'pos_label': '(1)'}), '(label, score, pos_label=1)\n', (9558, 9585), False, 'from sklearn import metrics\n'), ((9596, 9617), 'sklearn.metrics.auc', 'metrics.auc', (['fpr', 'tpr'], {}), '(fpr, tpr)\n', (9607, 9617), False, 'from sklearn import metrics\n'), ((10832, 10859), 'torch.save', 'torch.save', (['state', 'filename'], {}), '(state, filename)\n', (10842, 10859), False, 'import torch\n'), ((11747, 11886), 'pointnet2.data.TripletFaceDataset', 'TripletFaceDataset', ([], {'root': '""""""', 'n_triplets': 'args.num_triplet', 'n_points': 'args.num_points', 'class_nums': '(500)', 'transforms': 'None', 'extensions': '"""bcnc"""'}), "(root='', n_triplets=args.num_triplet, n_points=args.\n num_points, class_nums=500, transforms=None, extensions='bcnc')\n", (11765, 11886), False, 'from pointnet2.data import TripletFaceDataset\n'), ((12014, 12117), 'torch.utils.data.DataLoader', 'DataLoader', (['train_dataset'], {'batch_size': 'args.batch_size', 'shuffle': '(True)', 'num_workers': '(4)', 'pin_memory': '(True)'}), '(train_dataset, batch_size=args.batch_size, shuffle=True,\n num_workers=4, pin_memory=True)\n', (12024, 12117), False, 'from torch.utils.data import DataLoader\n'), ((12174, 12214), 'pointnet2.models.Pointnet2FaceClsSSG', 'Pointnet', ([], {'input_channels': '(3)', 'use_xyz': '(True)'}), '(input_channels=3, use_xyz=True)\n', (12182, 12214), True, 'from pointnet2.models import Pointnet2FaceClsSSG as Pointnet\n'), ((12537, 12574), 'torch.nn.TripletMarginLoss', 'nn.TripletMarginLoss', ([], {'margin': '(0.5)', 'p': '(2)'}), '(margin=0.5, p=2)\n', (12557, 12574), True, 'import torch.nn as nn\n'), ((3206, 3226), 'torch.norm', 'torch.norm', (['x1', '(2)', '(1)'], {}), '(x1, 2, 1)\n', (3216, 3226), False, 'import torch\n'), ((3243, 3263), 'torch.norm', 'torch.norm', (['x2', '(2)', '(1)'], {}), '(x2, 2, 1)\n', (3253, 3263), False, 'import torch\n'), ((3689, 3707), 'torch.abs', 'torch.abs', (['(x1 - x2)'], {}), '(x1 - x2)\n', (3698, 3707), False, 'import torch\n'), ((3775, 3812), 'torch.pow', 'torch.pow', (['(out + eps)', '(1.0 / self.norm)'], {}), '(out + eps, 1.0 / self.norm)\n', (3784, 3812), False, 'import torch\n'), ((4295, 4340), 'torch.clamp', 'torch.clamp', (['(self.margin + d_p - d_n)'], {'min': '(0.0)'}), '(self.margin + d_p - d_n, min=0.0)\n', (4306, 4340), False, 'import torch\n'), ((4356, 4378), 'torch.mean', 'torch.mean', (['dist_hinge'], {}), '(dist_hinge)\n', (4366, 4378), False, 'import torch\n'), ((6014, 6032), 'numpy.where', 'np.where', (['(all == 1)'], {}), '(all == 1)\n', (6022, 6032), True, 'import numpy as np\n'), ((6738, 6749), 'time.time', 'time.time', ([], {}), '()\n', (6747, 6749), False, 'import time\n'), ((7603, 7624), 'os.path.getsize', 'os.path.getsize', (['path'], {}), '(path)\n', (7618, 7624), False, 'import os\n'), ((8257, 8286), 'torch.set_grad_enabled', 'torch.set_grad_enabled', (['(False)'], {}), '(False)\n', (8279, 8286), False, 'import torch\n'), ((11030, 11048), 'os.listdir', 'os.listdir', (['folder'], {}), '(folder)\n', (11040, 11048), False, 'import os\n'), ((11100, 11127), 'os.path.join', 'os.path.join', (['folder', 'cname'], {}), '(folder, cname)\n', (11112, 11127), False, 'import os\n'), ((11146, 11163), 'os.listdir', 'os.listdir', (['cpath'], {}), '(cpath)\n', (11156, 11163), False, 'import os\n'), ((13655, 13679), 'os.path.isdir', 'osp.isdir', (['"""checkpoints"""'], {}), "('checkpoints')\n", (13664, 13679), True, 'import os.path as osp\n'), ((13689, 13715), 'os.makedirs', 'os.makedirs', (['"""checkpoints"""'], {}), "('checkpoints')\n", (13700, 13715), False, 'import os\n'), ((5510, 5546), 'torch.autograd.Variable', 'Variable', (['data_a'], {'requires_grad': '(True)'}), '(data_a, requires_grad=True)\n', (5518, 5546), False, 'from torch.autograd import Variable, Function\n'), ((5547, 5583), 'torch.autograd.Variable', 'Variable', (['data_p'], {'requires_grad': '(True)'}), '(data_p, requires_grad=True)\n', (5555, 5583), False, 'from torch.autograd import Variable, Function\n'), ((5584, 5620), 'torch.autograd.Variable', 'Variable', (['data_n'], {'requires_grad': '(True)'}), '(data_n, requires_grad=True)\n', (5592, 5620), False, 'from torch.autograd import Variable, Function\n'), ((7730, 7768), 'numpy.asarray', 'np.asarray', (['data_raw'], {'dtype': 'np.float32'}), '(data_raw, dtype=np.float32)\n', (7740, 7768), True, 'import numpy as np\n'), ((11214, 11240), 'os.path.join', 'os.path.join', (['cpath', 'gname'], {}), '(cpath, gname)\n', (11226, 11240), False, 'import os\n'), ((11674, 11709), 'pointnet2.data.data_utils.PointcloudJitter', 'd_utils.PointcloudJitter', ([], {'std': '(0.002)'}), '(std=0.002)\n', (11698, 11709), True, 'import pointnet2.data.data_utils as d_utils\n'), ((3722, 3748), 'torch.pow', 'torch.pow', (['diff', 'self.norm'], {}), '(diff, self.norm)\n', (3731, 3748), False, 'import torch\n'), ((5356, 5367), 'time.time', 'time.time', ([], {}), '()\n', (5365, 5367), False, 'import time\n'), ((6705, 6716), 'time.time', 'time.time', ([], {}), '()\n', (6714, 6716), False, 'import time\n'), ((3292, 3309), 'torch.mul', 'torch.mul', (['x1', 'x2'], {}), '(x1, x2)\n', (3301, 3309), False, 'import torch\n'), ((9273, 9297), 'numpy.argmax', 'np.argmax', (['Label'], {'axis': '(0)'}), '(Label, axis=0)\n', (9282, 9297), True, 'import numpy as np\n'), ((11512, 11531), 'numpy.array', 'np.array', (['[1, 0, 0]'], {}), '([1, 0, 0])\n', (11520, 11531), True, 'import numpy as np\n'), ((11576, 11595), 'numpy.array', 'np.array', (['[0, 1, 0]'], {}), '([0, 1, 0])\n', (11584, 11595), True, 'import numpy as np\n'), ((11640, 11659), 'numpy.array', 'np.array', (['[0, 0, 1]'], {}), '([0, 0, 1])\n', (11648, 11659), True, 'import numpy as np\n'), ((12300, 12346), 'pointnet2.train.layer.MarginCosineProduct', 'layer.MarginCosineProduct', (['(512)', 'args.num_class'], {}), '(512, args.num_class)\n', (12325, 12346), False, 'from pointnet2.train import layer\n'), ((12370, 12408), 'pointnet2.train.layer.AngleLinear', 'layer.AngleLinear', (['(512)', 'args.num_class'], {}), '(512, args.num_class)\n', (12387, 12408), False, 'from pointnet2.train import layer\n'), ((12432, 12480), 'torch.nn.Linear', 'torch.nn.Linear', (['(512)', 'args.num_class'], {'bias': '(False)'}), '(512, args.num_class, bias=False)\n', (12447, 12480), False, 'import torch\n'), ((9240, 9264), 'torch.argmax', 'torch.argmax', (['dis'], {'dim': '(0)'}), '(dis, dim=0)\n', (9252, 9264), False, 'import torch\n')] |
import numpy as np
from torch.utils.data.dataset import Dataset
import torch
from utils import matrix_to_pixel_frame_target
from torch import nn
class MyDataset(Dataset):
def __init__(self, dataset):
self.__dataset = dataset
def __getitem__(self, index):
data = self.__dataset[index]
pixel_id = np.array(data[0], dtype=int)
frame_id = np.array(data[1], dtype=int)
target = np.array(data[2], dtype=np.float32)
return torch.from_numpy(pixel_id), torch.from_numpy(frame_id), torch.from_numpy(target)
def __len__(self):
self.__size = self.__dataset.shape[0]
return self.__size
def load_dataset(matrix2d, batch_size, num_workers, train_test_split=None, valve=None):
print('getting ind matrix')
ind_mat = matrix_to_pixel_frame_target(matrix2d)
dataset = MyDataset(ind_mat)
if not train_test_split and not valve:
loader = torch.utils.data.DataLoader(dataset, batch_size=batch_size, shuffle=True, num_workers=num_workers,
drop_last=False)
loader = (loader, None)
elif train_test_split:
tot_num_samples = len(dataset)
n_train = int(tot_num_samples*train_test_split)
n_val = int(tot_num_samples*(1-train_test_split))
train_set, val_set = torch.utils.data.random_split(dataset, (n_train, n_val))
train_loader = torch.utils.data.DataLoader(train_set, batch_size=batch_size,
shuffle=True, num_workers=num_workers,
drop_last=False)
val_loader = torch.utils.data.DataLoader(val_set, batch_size=batch_size,
shuffle=True, num_workers=num_workers,
drop_last=False)
loader = (train_loader, val_loader)
else:
valve_frames = [int(list(v.keys())[0])-1 for v in valve]
ind_mat_train = ind_mat[ind_mat[:, 1] < (valve_frames[-1]+valve_frames[-2])/2]
ind_mat_val = ind_mat[ind_mat[:, 1] >= (valve_frames[-1] + valve_frames[-2]) / 2]
dataset_train = MyDataset(ind_mat_train)
dataset_val = MyDataset(ind_mat_val)
loader = (torch.utils.data.DataLoader(dataset_train, batch_size=batch_size, shuffle=True, num_workers=num_workers,
drop_last=False),
torch.utils.data.DataLoader(dataset_val, batch_size=batch_size, shuffle=True,
num_workers=num_workers,
drop_last=False))
return loader
class Swish(nn.Module):
'''
Implementation of swish.
Shape:
- Input: (N, *) where * means, any number of additional
dimensions
- Output: (N, *), same shape as the input
Parameters:
- beta - trainable parameter
'''
def __init__(self, beta=None):
'''
Initialization.
INPUT:
- beta: trainable parameter
beta is initialized with zero value by default
'''
super(Swish, self).__init__()
# initialize beta
if not beta:
beta = 0.
beta_tensor = torch.tensor(beta**2, dtype=torch.float, requires_grad=True)
self.beta = torch.nn.Parameter(beta_tensor**2, requires_grad=True) # create a tensor out of beta
def forward(self, input):
return input*torch.sigmoid(self.beta*input)
class EarlyStopping:
def __init__(self, mode='min', min_delta=0, patience=10, percentage=False):
self.mode = mode
self.min_delta = min_delta
self.patience = patience
self.best = None
self.num_bad_epochs = 0
self.is_better = None
self._init_is_better(mode, min_delta, percentage)
if patience == 0:
self.is_better = lambda a, b: True
self.step = lambda a: False
def step(self, metrics):
if self.best is None:
self.best = metrics
return False
if np.isnan(metrics):
return True
if self.is_better(metrics, self.best):
self.num_bad_epochs = 0
self.best = metrics
else:
self.num_bad_epochs += 1
if self.num_bad_epochs >= self.patience:
return True
return False
def _init_is_better(self, mode, min_delta, percentage):
if mode not in {'min', 'max'}:
raise ValueError('mode ' + mode + ' is unknown!')
if not percentage:
if mode == 'min':
self.is_better = lambda a, best: a < best - min_delta
if mode == 'max':
self.is_better = lambda a, best: a > best + min_delta
else:
if mode == 'min':
self.is_better = lambda a, best: a < best - (
best * min_delta / 100)
if mode == 'max':
self.is_better = lambda a, best: a > best + (
best * min_delta / 100) | [
"torch.nn.Parameter",
"torch.utils.data.DataLoader",
"utils.matrix_to_pixel_frame_target",
"numpy.isnan",
"torch.sigmoid",
"numpy.array",
"torch.utils.data.random_split",
"torch.tensor",
"torch.from_numpy"
] | [((792, 830), 'utils.matrix_to_pixel_frame_target', 'matrix_to_pixel_frame_target', (['matrix2d'], {}), '(matrix2d)\n', (820, 830), False, 'from utils import matrix_to_pixel_frame_target\n'), ((332, 360), 'numpy.array', 'np.array', (['data[0]'], {'dtype': 'int'}), '(data[0], dtype=int)\n', (340, 360), True, 'import numpy as np\n'), ((380, 408), 'numpy.array', 'np.array', (['data[1]'], {'dtype': 'int'}), '(data[1], dtype=int)\n', (388, 408), True, 'import numpy as np\n'), ((426, 461), 'numpy.array', 'np.array', (['data[2]'], {'dtype': 'np.float32'}), '(data[2], dtype=np.float32)\n', (434, 461), True, 'import numpy as np\n'), ((924, 1043), 'torch.utils.data.DataLoader', 'torch.utils.data.DataLoader', (['dataset'], {'batch_size': 'batch_size', 'shuffle': '(True)', 'num_workers': 'num_workers', 'drop_last': '(False)'}), '(dataset, batch_size=batch_size, shuffle=True,\n num_workers=num_workers, drop_last=False)\n', (951, 1043), False, 'import torch\n'), ((3286, 3348), 'torch.tensor', 'torch.tensor', (['(beta ** 2)'], {'dtype': 'torch.float', 'requires_grad': '(True)'}), '(beta ** 2, dtype=torch.float, requires_grad=True)\n', (3298, 3348), False, 'import torch\n'), ((3367, 3423), 'torch.nn.Parameter', 'torch.nn.Parameter', (['(beta_tensor ** 2)'], {'requires_grad': '(True)'}), '(beta_tensor ** 2, requires_grad=True)\n', (3385, 3423), False, 'import torch\n'), ((4120, 4137), 'numpy.isnan', 'np.isnan', (['metrics'], {}), '(metrics)\n', (4128, 4137), True, 'import numpy as np\n'), ((478, 504), 'torch.from_numpy', 'torch.from_numpy', (['pixel_id'], {}), '(pixel_id)\n', (494, 504), False, 'import torch\n'), ((506, 532), 'torch.from_numpy', 'torch.from_numpy', (['frame_id'], {}), '(frame_id)\n', (522, 532), False, 'import torch\n'), ((534, 558), 'torch.from_numpy', 'torch.from_numpy', (['target'], {}), '(target)\n', (550, 558), False, 'import torch\n'), ((1326, 1382), 'torch.utils.data.random_split', 'torch.utils.data.random_split', (['dataset', '(n_train, n_val)'], {}), '(dataset, (n_train, n_val))\n', (1355, 1382), False, 'import torch\n'), ((1406, 1527), 'torch.utils.data.DataLoader', 'torch.utils.data.DataLoader', (['train_set'], {'batch_size': 'batch_size', 'shuffle': '(True)', 'num_workers': 'num_workers', 'drop_last': '(False)'}), '(train_set, batch_size=batch_size, shuffle=True,\n num_workers=num_workers, drop_last=False)\n', (1433, 1527), False, 'import torch\n'), ((1647, 1766), 'torch.utils.data.DataLoader', 'torch.utils.data.DataLoader', (['val_set'], {'batch_size': 'batch_size', 'shuffle': '(True)', 'num_workers': 'num_workers', 'drop_last': '(False)'}), '(val_set, batch_size=batch_size, shuffle=True,\n num_workers=num_workers, drop_last=False)\n', (1674, 1766), False, 'import torch\n'), ((3505, 3537), 'torch.sigmoid', 'torch.sigmoid', (['(self.beta * input)'], {}), '(self.beta * input)\n', (3518, 3537), False, 'import torch\n'), ((2269, 2395), 'torch.utils.data.DataLoader', 'torch.utils.data.DataLoader', (['dataset_train'], {'batch_size': 'batch_size', 'shuffle': '(True)', 'num_workers': 'num_workers', 'drop_last': '(False)'}), '(dataset_train, batch_size=batch_size, shuffle=\n True, num_workers=num_workers, drop_last=False)\n', (2296, 2395), False, 'import torch\n'), ((2456, 2580), 'torch.utils.data.DataLoader', 'torch.utils.data.DataLoader', (['dataset_val'], {'batch_size': 'batch_size', 'shuffle': '(True)', 'num_workers': 'num_workers', 'drop_last': '(False)'}), '(dataset_val, batch_size=batch_size, shuffle=\n True, num_workers=num_workers, drop_last=False)\n', (2483, 2580), False, 'import torch\n')] |
import numpy as np
import numpy.linalg as la
import cupy as cp
src_files = [
'../../xfields/src_autogenerated/linear_interpolators_cuda.cu']
src_content = 'extern "C"{'
for ff in src_files:
with open(ff, 'r') as fid:
src_content += ('\n\n' + fid.read())
src_content += "}"
module = cp.RawModule(code=src_content)
knl_p2m_rectmesh3d= module.get_function('p2m_rectmesh3d')
knl_m2p_rectmesh3d= module.get_function('m2p_rectmesh3d')
import pickle
with open('../000_sphere/picsphere.pkl', 'rb') as fid:
ddd = pickle.load(fid)
fmap = ddd['fmap']
x0 = fmap.x_grid[0]
y0 = fmap.y_grid[0]
z0 = fmap.z_grid[0]
dx = fmap.dx
dy = fmap.dy
dz = fmap.dz
nx = fmap.nx
ny = fmap.ny
nz = fmap.nz
pos_in_buffer_of_maps_to_interp = []
mapsize = fmap.nx*fmap.ny*fmap.nz
pos_in_buffer_of_maps_to_interp.append(0*mapsize)
pos_in_buffer_of_maps_to_interp.append(1*mapsize)
pos_in_buffer_of_maps_to_interp.append(2*mapsize)
pos_in_buffer_of_maps_to_interp.append(3*mapsize)
pos_in_buffer_of_maps_to_interp.append(4*mapsize)
nmaps_to_interp = len(pos_in_buffer_of_maps_to_interp)
x_dev = cp.array(ddd['x_test'])
y_dev = cp.array(ddd['y_test'])
z_dev = cp.array(ddd['z_test'])
n_particles = len(x_dev)
dev_offsets = cp.array(np.array(pos_in_buffer_of_maps_to_interp,
dtype=np.int32))
dev_maps_buff = cp.array(fmap._maps_buffer)
dev_out_buff = cp.array(np.zeros(nmaps_to_interp*n_particles))
n_threads = n_particles
block_size = 256
grid_size = int(np.ceil(n_particles/block_size))
knl_m2p_rectmesh3d((grid_size, ), (block_size, ), (
np.int32(n_particles),
x_dev.data, y_dev.data, z_dev.data,
x0, y0, z0, dx, dy, dz,
np.int32(nx), np.int32(ny), np.int32(nz),
np.int32(nmaps_to_interp),
dev_offsets.data, dev_maps_buff.data,
dev_out_buff.data))
# Test p2m
n_gen = 1000000
x_gen_dev = cp.array(
np.zeros([n_gen], dtype=np.float64)+fmap.x_grid[10])
y_gen_dev = cp.array(
np.zeros([n_gen], dtype=np.float64)+fmap.y_grid[10])
z_gen_dev = cp.array(
np.zeros([n_gen], dtype=np.float64)+fmap.z_grid[10])
part_weights_dev = cp.array(
np.zeros([n_gen], dtype=np.float64)+1.)
maps_buff = cp.array(0*fmap._maps_buffer)
dev_rho = maps_buff[:,:,:,1]
block_size = 256
grid_size = int(np.ceil(n_gen/block_size))
import time
t1 = time.time()
knl_p2m_rectmesh3d((grid_size, ), (block_size, ), (
np.int32(n_gen),
x_gen_dev.data, y_gen_dev.data, z_gen_dev.data,
part_weights_dev.data,
x0, y0, z0, dx, dy, dz,
np.int32(nx), np.int32(ny), np.int32(nz),
dev_rho.data))
a = dev_rho[10,10,10]
t2 = time.time()
print(f't = {t2-t1:.2e}')
| [
"cupy.RawModule",
"numpy.ceil",
"cupy.array",
"numpy.zeros",
"time.time",
"pickle.load",
"numpy.array",
"numpy.int32"
] | [((302, 332), 'cupy.RawModule', 'cp.RawModule', ([], {'code': 'src_content'}), '(code=src_content)\n', (314, 332), True, 'import cupy as cp\n'), ((1094, 1117), 'cupy.array', 'cp.array', (["ddd['x_test']"], {}), "(ddd['x_test'])\n", (1102, 1117), True, 'import cupy as cp\n'), ((1126, 1149), 'cupy.array', 'cp.array', (["ddd['y_test']"], {}), "(ddd['y_test'])\n", (1134, 1149), True, 'import cupy as cp\n'), ((1158, 1181), 'cupy.array', 'cp.array', (["ddd['z_test']"], {}), "(ddd['z_test'])\n", (1166, 1181), True, 'import cupy as cp\n'), ((1309, 1336), 'cupy.array', 'cp.array', (['fmap._maps_buffer'], {}), '(fmap._maps_buffer)\n', (1317, 1336), True, 'import cupy as cp\n'), ((2176, 2207), 'cupy.array', 'cp.array', (['(0 * fmap._maps_buffer)'], {}), '(0 * fmap._maps_buffer)\n', (2184, 2207), True, 'import cupy as cp\n'), ((2314, 2325), 'time.time', 'time.time', ([], {}), '()\n', (2323, 2325), False, 'import time\n'), ((2622, 2633), 'time.time', 'time.time', ([], {}), '()\n', (2631, 2633), False, 'import time\n'), ((529, 545), 'pickle.load', 'pickle.load', (['fid'], {}), '(fid)\n', (540, 545), False, 'import pickle\n'), ((1230, 1287), 'numpy.array', 'np.array', (['pos_in_buffer_of_maps_to_interp'], {'dtype': 'np.int32'}), '(pos_in_buffer_of_maps_to_interp, dtype=np.int32)\n', (1238, 1287), True, 'import numpy as np\n'), ((1361, 1400), 'numpy.zeros', 'np.zeros', (['(nmaps_to_interp * n_particles)'], {}), '(nmaps_to_interp * n_particles)\n', (1369, 1400), True, 'import numpy as np\n'), ((1458, 1491), 'numpy.ceil', 'np.ceil', (['(n_particles / block_size)'], {}), '(n_particles / block_size)\n', (1465, 1491), True, 'import numpy as np\n'), ((2269, 2296), 'numpy.ceil', 'np.ceil', (['(n_gen / block_size)'], {}), '(n_gen / block_size)\n', (2276, 2296), True, 'import numpy as np\n'), ((1552, 1573), 'numpy.int32', 'np.int32', (['n_particles'], {}), '(n_particles)\n', (1560, 1573), True, 'import numpy as np\n'), ((1659, 1671), 'numpy.int32', 'np.int32', (['nx'], {}), '(nx)\n', (1667, 1671), True, 'import numpy as np\n'), ((1673, 1685), 'numpy.int32', 'np.int32', (['ny'], {}), '(ny)\n', (1681, 1685), True, 'import numpy as np\n'), ((1687, 1699), 'numpy.int32', 'np.int32', (['nz'], {}), '(nz)\n', (1695, 1699), True, 'import numpy as np\n'), ((1709, 1734), 'numpy.int32', 'np.int32', (['nmaps_to_interp'], {}), '(nmaps_to_interp)\n', (1717, 1734), True, 'import numpy as np\n'), ((1868, 1903), 'numpy.zeros', 'np.zeros', (['[n_gen]'], {'dtype': 'np.float64'}), '([n_gen], dtype=np.float64)\n', (1876, 1903), True, 'import numpy as np\n'), ((1951, 1986), 'numpy.zeros', 'np.zeros', (['[n_gen]'], {'dtype': 'np.float64'}), '([n_gen], dtype=np.float64)\n', (1959, 1986), True, 'import numpy as np\n'), ((2034, 2069), 'numpy.zeros', 'np.zeros', (['[n_gen]'], {'dtype': 'np.float64'}), '([n_gen], dtype=np.float64)\n', (2042, 2069), True, 'import numpy as np\n'), ((2124, 2159), 'numpy.zeros', 'np.zeros', (['[n_gen]'], {'dtype': 'np.float64'}), '([n_gen], dtype=np.float64)\n', (2132, 2159), True, 'import numpy as np\n'), ((2386, 2401), 'numpy.int32', 'np.int32', (['n_gen'], {}), '(n_gen)\n', (2394, 2401), True, 'import numpy as np\n'), ((2530, 2542), 'numpy.int32', 'np.int32', (['nx'], {}), '(nx)\n', (2538, 2542), True, 'import numpy as np\n'), ((2544, 2556), 'numpy.int32', 'np.int32', (['ny'], {}), '(ny)\n', (2552, 2556), True, 'import numpy as np\n'), ((2558, 2570), 'numpy.int32', 'np.int32', (['nz'], {}), '(nz)\n', (2566, 2570), True, 'import numpy as np\n')] |
import numpy as np
from scipy.optimize import leastsq
from .save_and_load import save_func, load_svA, load_hvdMdh
from .param_dict import split_dict, get_keys, separate_params, generate_dict_with_fixed_params, split_dict_with_fixed_params
from .residuals import As_residual, dMdh_residual
from .residuals import Sigma_residual, eta_residual, joint_residual
from .print_fit_info import print_fit_info
params0_dict = {
'Sigma_power law': dict([('rScale', 1.0), ('rc', 0.0), ('sScale', 1.0), ('sigma', 0.1)]),
'Sigma_truncated': dict([('rScale', 1.0), ('rc', 0.0), ('sScale', 10.0), ('df', 2.0), ('B', 0.1), ('C', 1.0)]),
'Sigma_well-behaved': dict([('rScale', 1.0), ('rc', 0.0), ('sScale', 10.0), ('df', 2.0), ('B', 0.1), ('C', 1.0)]),
'Sigma_pitchfork': dict([('rScale', 1.0), ('rc', 0.0), ('sScale', 1.0), ('df', 2.0), ('B', 10.0), ('C', 1.0)]),
'eta_power law': dict([('rScale', 1.0), ('rc', 0.0), ('etaScale', 0.3), ('betaDelta',1.0)]),
'eta_truncated': dict([('rScale', 1.0), ('rc', 0.0), ('etaScale', 0.3), ('lambdaH', 1.0), ('B', 1.0), ('F', 0.1)]),
'eta_well-behaved': dict([('rScale', 1.0), ('rc', 0.0), ('etaScale', 0.3), ('lambdaH', 1.0), ('B', 1.0), ('F', 0.1)]),
'eta_pitchfork': dict([('rScale', 5.0), ('rc', 0.0), ('etaScale', 130.0), ('lambdaH', 0.6), ('B', 4.0), ('F', 1.8)]),
'joint_power law': dict([('rScale', 1.0), ('rc', 0.0), ('sScale', 1.0), ('etaScale', 1.0), ('sigma', 0.1), ('betaDelta', 1.0)]),
'joint_truncated': dict([('rScale', 1.0), ('rc', 0.0), ('sScale', 10.), ('etaScale', 1.0), ('df', 1.0), ('lambdaH', 1.0), ('B', 0.1), ('C', 1.0), ('F', 1.0)]),
'joint_well-behaved': dict([('rScale', 1.0), ('rc', 0.0), ('sScale', 10.), ('etaScale', 1.0), ('df', 1.0), ('lambdaH', 1.0), ('B', 0.1), ('C', 1.0), ('F', 1.0)]),
'joint_pitchfork': dict([('rScale', 5.0), ('rc', 0.0), ('sScale', -1.0), ('etaScale', 100.0), ('df', 2.0), ('lambdaH', 1.0), ('B', 0.0), ('C', 10.0), ('F', 2.0)]),
}
default_fixed = dict([('df',2.), ('C',0.)])
def perform_fit(residual_func, params0, args, verbose=False):
"""
Function to print beginning cost, perform fit and subsequently
print ending cost
Input:
residual_func - function which provides the residual
params0 - initial guess for parameters
args - arguments which remain fixed in the residual function
verbose - flag to print cost
Output:
params - best fit value of the parameters
err - error in the fit
"""
if isinstance(params0, dict):
keys, params0 = split_dict(params0)
res = residual_func(params0, args)
if verbose:
print('initial cost=', (res*res).sum())
params, err = leastsq(residual_func, params0, args=args)
res = residual_func(params, args)
if verbose:
print('cost=', (res*res).sum())
return params, err
def save_and_show(params, fit_type, func_type='well-behaved',
filename=None, show=True):
"""
Save fit parameters and/or plot fit information in figure format
"""
assert(isinstance(params, dict))
if filename is not None:
save_func(filename+'.pkl.gz', params)
print_fit_info(params, fit_type, func_type=func_type,
filename=filename+'.png', show=False)
if show:
print_fit_info(params, fit_type, func_type=func_type, show=True)
return
def fit_As_Scaling(args, params0=None, filename=None,
verbose=False, show_params=True):
"""
Perform the fit of A(s)
Input:
args - s_list, As_list
s_list - list of avalanche size values obtained from simulation
As_list - corresponding values of area weighted size
distribution times avalanche size at the
given values of s in s_list
params0 - optional initial values for the constants in the
functional form of As
filename - data is saved under 'filename' if a file name is given
verbose - flag to print cost
show_params - flag for whether to plot parameter names
with their values
Output:
params - best fit values for the constants in the functional
form of dMdh
err - error of the fit
"""
s_list, As_list = args
num_curves = len(s_list)
if params0 is None:
zipped = zip(As_list, s_list)
Sigma0 = [(As[:-1]*(s[1:]-s[:-1])).sum() for As, s in zipped]
constants = np.array([0.8, 1.0])
params0 = np.concatenate([Sigma0, constants])
params, err = perform_fit(As_residual, params0, args, verbose=verbose)
Sigma = params[:num_curves]
a, b = params[num_curves:]
keys = get_keys('A')
values = [Sigma, a, b]
params = dict(zip(keys, values))
save_and_show(params, 'A', filename=filename, show=show_params)
return params, err
def fit_dMdh_Scaling(args, params0=None, weight_list=None, filename=None,
verbose=False, show_params=True):
"""
Perform the fit of dMdh(h)
Input:
args - h_list, dMdh_list
h_list - list of field values obtained from simulation
dMdh_list - corresponding values of dM/dh at the given values
of h in h_list
params0 - optional initial values for the constants in the
functional form of dMdh
weight_list - weighting for the importance of different
curves in the fit
filename - data is saved under 'filename' if a file name is given
verbose - flag to print cost
show_params - flag for whether to plot parameter names
with their values
Output:
params - best fit values for the constants in the functional
form of dMdh
err - error of the fit
"""
h_list, dMdh_list = args
num_curves = len(h_list)
if params0 is None:
zipped = zip(h_list, dMdh_list)
hmax0 = np.array([h[np.argmax(dMdh)] for h, dMdh in zipped])
eta0 = np.array([np.sqrt(np.pi/2)/max(dMdh) for dMdh in dMdh_list])
constants = np.array([0.36, 0.0, 0.36, 1.0])
params0 = np.concatenate([hmax0, eta0, constants])
if weight_list is None:
weight_list = 1.0/eta0
allargs = [h_list, dMdh_list, weight_list]
params, err = perform_fit(dMdh_residual, params0, allargs,
verbose=verbose)
hMax = params[:num_curves]
eta = params[num_curves:2*num_curves]
a, b, c, d = params[2*num_curves:]
keys = get_keys('dMdh')
values = [hMax, eta, a, b, c, d]
params = dict(zip(keys, values))
save_and_show(params, 'dMdh', filename=filename, show=show_params)
return params, err
def get_Sigma(filename=None, data=None, show_params=False):
"""
Perform the fit of A and return (r, Sigma) pairs
"""
if data is None:
r, s, A, As = load_svA(filename)
else:
r, s, A, As = data
params, err = fit_As_Scaling([s, As], show_params=show_params)
return r, params['Sigma']
def Sigma_fit(args, params0=None, fixed_dict=default_fixed,
func_type='well-behaved', filename=None,
verbose=False, show_params=True):
"""
Perform the fit of Sigma(r)
Input:
args - r_list, Sigma
r_list - list of r values for which there are
values of Sigma and eta
Sigma - list of Sigma values at each r
params0 - optional initial values for the constants
in the functional form of Sigma
fixed_dict - dictionary of parameters to be fixed
func_type - which form of Sigma(r) to use. Options:
'power law' - Sigma(r) derived with dw/dl = (1/nu) w
'truncated' - Sigma(r) derived with dw/dl = w^2 + B w^3
'well-behaved' - Sigma(r) derived with dw/dl = w^2 / (1 + B w)
'pitchfork' - Sigma(r) derived with dw/dl = w^3 + B w^5
filename - data is saved under 'filename' if a file name is given
verbose - flag to print cost
show_params - flag for whether to plot parameter names with
their values
Output:
params - best fit values for the constants in the functional
form of Sigma
err - error of the fit
"""
r_list, Sigma = args
if params0 is None:
params0_key = 'Sigma_'+func_type
params0 = params0_dict[params0_key]
if fixed_dict is not None:
keys = list(params0.copy().keys())
params0 = split_dict_with_fixed_params(params0, fixed_dict)
else:
keys, params0 = split_dict(params0)
fullargs = [r_list, Sigma, keys, fixed_dict, func_type]
params, err = perform_fit(Sigma_residual, params0, fullargs,
verbose=verbose)
param_dict = generate_dict_with_fixed_params(params, keys, fixed_dict)
save_and_show(param_dict, 'Sigma', func_type=func_type,
filename=filename, show=show_params)
return param_dict, err
def get_eta(filename=None, data=None, show_params=False):
"""
Perform the fit of dMdh and return (r, eta) pairs
"""
if data is None:
r, h, dMdh = load_hvdMdh(filename)
else:
r, h, dMdh = data
params, err = fit_dMdh_Scaling([h, dMdh], show_params=show_params)
return r, params['eta']
def eta_fit(args, params0=None, fixed_dict=default_fixed, func_type='well-behaved',
filename=None, verbose=False, show_params=True):
"""
Perform the fit of eta(r)
Input:
args - r_list, eta
r_list - list of r values for which there are values
of Sigma and eta
eta - list of eta values at each r
params0 - optional initial values for the constants in the
functional form of eta
fixed_dict - dictionary of parameters to be fixed
func_type - which form of eta(r) to use. Options:
'power law' - eta(r) derived with dw/dl = (1/nu) w
'truncated' - eta(r) derived with dw/dl = w^2 + B w^3
'well-behaved' - eta(r) derived with dw/dl = w^2 / (1 + B w)
'pitchfork' - eta(r) derived with dw/dl = w^3 + B w^5
filename - data is saved under 'filename' if a file name is given
verbose - flag to print cost
show_params - flag for whether to plot parameter names
with their values
Output:
params - best fit values for the constants in the functional
form of eta
err - error of the fit
"""
r_list, eta = args
if params0 is None:
params0_key = 'eta_'+func_type
params0 = params0_dict[params0_key]
if fixed_dict is not None:
keys = list(params0.copy().keys())
params0 = split_dict_with_fixed_params(params0, fixed_dict)
else:
keys, params0 = split_dict(params0)
fullargs = [r_list, eta, keys, fixed_dict, func_type]
params, err = perform_fit(eta_residual, params0, fullargs,
verbose=verbose)
param_dict = generate_dict_with_fixed_params(params, keys, fixed_dict)
save_and_show(param_dict, 'eta', func_type=func_type,
filename=filename, show=show_params)
return param_dict, err
def joint_fit(args, params0=None, fixed_dict=default_fixed,
func_type='well-behaved', filename=None,
verbose=False, show_params=True):
"""
Perform the joint fit of Sigma(r) and eta(r)
Input:
args - rA, Sigma, rdMdh, eta
rA - list of r values for which there are values Sigma
Sigma - list of Sigma values at each r
rdMdh - list of r values for which there are values of eta
eta - list of eta values at each r
params0 - optional initial values for the constants in the
functional forms of Sigma and eta
fixed_dict - dictionary of parameters to be fixed
func_type - which form of eta(r) to use. Options:
'power law' - eta(r) derived with dw/dl = (1/nu) w
'truncated' - eta(r) derived with dw/dl = w^2 + B w^3
'well-behaved' - eta(r) derived with dw/dl = w^2 / (1 + B w)
'pitchfork' - eta(r) derived with dw/dl = w^3 + B w^5
filename - data is saved under 'filename' if a file name is given
verbose - flag to print cost
show_params - flag for whether to plot parameter names
with their values
Output:
params - best fit values for the constants in the functional
forms of Sigma and eta
err - error of the fit
"""
rA, Sigma, rdMdh, eta = args
if params0 is None:
params0_key = 'joint_'+func_type
params0 = params0_dict[params0_key]
if fixed_dict is not None:
keys = list(params0.copy().keys())
params0 = split_dict_with_fixed_params(params0, fixed_dict)
else:
keys, params0 = split_dict(params0)
fullargs = [rA, Sigma, rdMdh, eta, keys, fixed_dict, func_type]
params, err = perform_fit(joint_residual, params0, fullargs,
verbose=verbose)
param_dict = generate_dict_with_fixed_params(params, keys, fixed_dict)
save_and_show(param_dict, 'joint', func_type=func_type,
filename=filename, show=show_params)
return param_dict, err
def perform_all_fits(filenames=[None, None], data=None,
fixed_dict=default_fixed, func_type='well-behaved',
verbose=False, show_params=True):
"""
Perform the fit of A, dMdh, Sigma and eta and return values
Input:
filenames - [A_filename, dMdh_filename]
- filenames to load data from
A_filename - location where area weighted
size distribution is stored
dMdh_filename - location where dM/dh data is stored
data - [dataA, datadMdh] - if filenames==None, checks to see if
data was provided here manually
dataA - [r, s, A, As]
datadMdh - [r, h, dMdh]
fixed_dict - dictionary of parameters to be fixed
func_type - which form of Sigma(r) to use. Options:
'power law' - Sigma(r) derived with dw/dl = (1/nu) w
'truncated' - Sigma(r) derived with dw/dl = w^2 + B w^3
'well-behaved' - Sigma(r) derived with dw/dl = w^2 / (1 + B w)
'pitchfork' - Sigma(r) derived with dw/dl = w^3 + B w^5
save - whether to save the fit data
verbose - flag to print cost
show_params - flag for whether to plot parameter names
with their values
Output:
params_A - fit values found for A
params_dMdh - fit values found for dM/dh
params_Sigma - fit values found for Sigma
params_eta - fit values found for eta
"""
if data is None:
rA, s, A, As = load_svA(filename=filenames[0])
rdMdh, h, dMdh = load_hvdMdh(filename=filenames[1])
else:
rA, s, A, As = data[0]
rdMdh, h, dMdh = data[1]
args_A = [s, As]
params_A, err = fit_As_Scaling(args_A, verbose=verbose,
show_params=show_params)
Sigma = params_A['Sigma']
args_dMdh = [h, dMdh]
params_dMdh, err = fit_dMdh_Scaling(args_dMdh, verbose=verbose,
show_params=show_params)
eta = params_dMdh['eta']
args = [rA, Sigma, rdMdh, eta]
params, err = joint_fit(args, fixed_dict=fixed_dict,
func_type=func_type, verbose=verbose,
show_params=show_params)
params_Sigma, params_eta = separate_params(params, func_type=func_type)
return params_A, params_dMdh, params_Sigma, params_eta
def compare_fits(r, Sigma, eta):
"""
Get params for fits to 3 forms (used to produce Figure 3:
see plotting.py 'plot_Sigma_compare_with_eta_inset')
"""
#power law
params0_powerlaw = dict([('rScale',1.0), ('rc', 0.0),
('sScale', 10.), ('etaScale', 1.0),
('sigma', 0.1), ('betaDelta', 1.0),
('B', 1.0)])
fixed_dict = None
params_powerlaw, err = joint_fit([r,Sigma,r,eta], fixed_dict=fixed_dict,
func_type='power law', params0=params0_powerlaw,
verbose=False, show_params=False)
#pitchfork
params0_pitchfork = dict([('rScale',1.0), ('rc', 0.0),
('sScale', 10.), ('etaScale', 1.0),
('df', 2.0), ('lambdaH', 1.0),
('B', 1.0), ('C', 0.0),
('F', 1.0)])
fixed_dict = None
params_pitchfork, err = joint_fit([r,Sigma,r,eta], fixed_dict=fixed_dict,
func_type='pitchfork', params0=params0_pitchfork,
verbose=False, show_params=False)
#truncated
params0_truncated = dict([('rScale',1.0), ('rc', 0.0),
('sScale', 10.), ('etaScale', 1.0),
('df', 2.0), ('lambdaH', 1.0),
('B', 1.0), ('C', 0.0),
('F', 1.0)])
fixed_dict = dict([('df',2.),('C',0.)])
params_truncated, err = joint_fit([r,Sigma,r,eta], fixed_dict=fixed_dict,
func_type='truncated',params0=params0_truncated,
verbose=False, show_params=False)
return params_powerlaw, params_pitchfork, params_truncated
| [
"numpy.argmax",
"scipy.optimize.leastsq",
"numpy.array",
"numpy.concatenate",
"numpy.sqrt"
] | [((2702, 2744), 'scipy.optimize.leastsq', 'leastsq', (['residual_func', 'params0'], {'args': 'args'}), '(residual_func, params0, args=args)\n', (2709, 2744), False, 'from scipy.optimize import leastsq\n'), ((4512, 4532), 'numpy.array', 'np.array', (['[0.8, 1.0]'], {}), '([0.8, 1.0])\n', (4520, 4532), True, 'import numpy as np\n'), ((4551, 4586), 'numpy.concatenate', 'np.concatenate', (['[Sigma0, constants]'], {}), '([Sigma0, constants])\n', (4565, 4586), True, 'import numpy as np\n'), ((6169, 6201), 'numpy.array', 'np.array', (['[0.36, 0.0, 0.36, 1.0]'], {}), '([0.36, 0.0, 0.36, 1.0])\n', (6177, 6201), True, 'import numpy as np\n'), ((6220, 6260), 'numpy.concatenate', 'np.concatenate', (['[hmax0, eta0, constants]'], {}), '([hmax0, eta0, constants])\n', (6234, 6260), True, 'import numpy as np\n'), ((6032, 6047), 'numpy.argmax', 'np.argmax', (['dMdh'], {}), '(dMdh)\n', (6041, 6047), True, 'import numpy as np\n'), ((6098, 6116), 'numpy.sqrt', 'np.sqrt', (['(np.pi / 2)'], {}), '(np.pi / 2)\n', (6105, 6116), True, 'import numpy as np\n')] |
import numpy as np
def custom_print(context, log_file, mode):
#custom print and log out function
if mode == 'w':
fp = open(log_file, mode)
fp.write(context + '\n')
fp.close()
elif mode == 'a+':
print(context)
fp = open(log_file, mode)
print(context, file=fp)
fp.close()
else:
raise Exception('other file operation is unimplemented !')
def generate_binary_map(pred, type,th=0.5):
if type == '2mean':
threshold = np.mean(pred) * 2
if threshold > th:
threshold = th
binary_map = pred > threshold
return binary_map.astype(np.float32)
if type == 'mean+std':
threshold = np.mean(pred) + np.std(pred)
if threshold > th:
threshold = th
binary_map = pred > threshold
return binary_map.astype(np.float32)
def calc_precision_and_jaccard(pred, gt,th=0.5):
bin_pred = generate_binary_map(pred, 'mean+std',th)
tp = (bin_pred == gt).sum()
precision = tp / (pred.size)
i = (bin_pred * gt).sum()
u = bin_pred.sum() + gt.sum() - i
jaccard = i / (u + 1e-10)
return precision, jaccard | [
"numpy.std",
"numpy.mean"
] | [((506, 519), 'numpy.mean', 'np.mean', (['pred'], {}), '(pred)\n', (513, 519), True, 'import numpy as np\n'), ((709, 722), 'numpy.mean', 'np.mean', (['pred'], {}), '(pred)\n', (716, 722), True, 'import numpy as np\n'), ((725, 737), 'numpy.std', 'np.std', (['pred'], {}), '(pred)\n', (731, 737), True, 'import numpy as np\n')] |
import tensorflow as tf
import numpy as np
import random
# from tensorflow.python.ops import rnn
from tensorflow.contrib import rnn
from data_preprocessing import get_audio_dataset_features_labels, get_audio_test_dataset_filenames, get_audio_test_dataset_features_labels, normalize_training_dataset, normalize_test_dataset
def shuffle_randomize(dataset_features, dataset_labels):
dataset_combined = list(zip(dataset_features, dataset_labels))
random.shuffle(dataset_combined)
dataset_features[:], dataset_labels[:] = zip(*dataset_combined)
return dataset_features, dataset_labels
def get_batch(dataset, i, BATCH_SIZE):
if i*BATCH_SIZE+BATCH_SIZE > dataset.shape[0]:
return dataset[i*BATCH_SIZE:, :], dataset.shape[0] - i*BATCH_SIZE
return dataset[i*BATCH_SIZE:(i*BATCH_SIZE+BATCH_SIZE), :], BATCH_SIZE
#DATASET_PATH = 'G:/DL/tf_speech_recognition'
DATASET_PATH = '/home/paperspace/tf_speech_recognition'
ALLOWED_LABELS = ['yes', 'no', 'up', 'down', 'left', 'right', 'on', 'off', 'stop', 'go', 'silence', 'unknown']
ALLOWED_LABELS_MAP = {}
for i in range(0, len(ALLOWED_LABELS)):
ALLOWED_LABELS_MAP[str(i)] = ALLOWED_LABELS[i]
dataset_train_features, dataset_train_labels, labels_one_hot_map = get_audio_dataset_features_labels(DATASET_PATH, ALLOWED_LABELS, type='train')
audio_filenames = get_audio_test_dataset_filenames(DATASET_PATH)
print('dataset_train_features.shape:', dataset_train_features.shape, 'dataset_train_labels.shape:', dataset_train_labels.shape)
# normalize training and testing features dataset
print('Normalizing datasets')
dataset_train_features, min_value, max_value = normalize_training_dataset(dataset_train_features)
# randomize shuffle
print('Shuffling training dataset')
dataset_train_features, dataset_train_labels = shuffle_randomize(dataset_train_features, dataset_train_labels)
# divide training set into training and validation
dataset_validation_features, dataset_validation_labels = dataset_train_features[57000:dataset_train_features.shape[0], :], dataset_train_labels[57000:dataset_train_labels.shape[0], :]
dataset_train_features, dataset_train_labels = dataset_train_features[0:57000, :], dataset_train_labels[0:57000, :]
print('dataset_validation_features.shape:', dataset_validation_features.shape, 'dataset_validation_labels.shape:', dataset_validation_labels.shape)
CLASSES = ['yes', 'no', 'up', 'down', 'left', 'right', 'on', 'off', 'stop', 'go', 'silence', 'unknown']
NUM_CLASSES = len(CLASSES)
NUM_EXAMPLES = dataset_train_features.shape[0]
NUM_CHUNKS = dataset_train_features.shape[1] # 161
CHUNK_SIZE = dataset_train_features.shape[2] # 99
NUM_EPOCHS = 100
BATCH_SIZE = 32
x = tf.placeholder(tf.float32, shape=[None, NUM_CHUNKS, CHUNK_SIZE])
y = tf.placeholder(tf.float32, shape=[None, NUM_CLASSES])
current_batch_size = tf.placeholder(tf.int32)
def recurrent_neural_network(x, current_batch_size):
lstm_cell_1 = rnn.LSTMCell(128, state_is_tuple=True)
lstm_cell_2 = rnn.LSTMCell(256, state_is_tuple=True)
lstm_cell_3 = rnn.LSTMCell(384, state_is_tuple=True)
multi_lstm_cells = rnn.MultiRNNCell([lstm_cell_1, lstm_cell_2, lstm_cell_3], state_is_tuple=True)
lstm_layer_1, lstm_layer_1_states = tf.nn.dynamic_rnn(multi_lstm_cells, x, dtype=tf.float32)
lstm_layer_1 = tf.reshape(lstm_layer_1, [-1, 161*384])
weights_1 = tf.Variable(tf.random_normal([161*384, 128]), dtype=tf.float32)
weights_2 = tf.Variable(tf.random_normal([128, NUM_CLASSES]), dtype=tf.float32)
biases_1 = tf.Variable(tf.random_normal([128]), dtype=tf.float32)
biases_2 = tf.Variable(tf.random_normal([NUM_CLASSES]), dtype=tf.float32)
fully_connected_1 = tf.matmul(lstm_layer_1, weights_1) + biases_1
fully_connected_2 = tf.matmul(fully_connected_1, weights_2) + biases_2
return fully_connected_2
logits = recurrent_neural_network(x, current_batch_size)
loss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=logits, labels=y))
optimizer = tf.train.AdamOptimizer()
training = optimizer.minimize(loss)
with tf.Session() as sess:
sess.run(tf.global_variables_initializer()) # initialize all global variables, which includes weights and biases
# training start
for epoch in range(0, NUM_EPOCHS):
total_cost = 0
for i in range(0, int(NUM_EXAMPLES/BATCH_SIZE)):
batch_x, batch_current_batch_size = get_batch(dataset_train_features, i, BATCH_SIZE) # get batch of features of size BATCH_SIZE
batch_y, _ = get_batch(dataset_train_labels, i, BATCH_SIZE) # get batch of labels of size BATCH_SIZE
_, batch_cost = sess.run([training, loss], feed_dict={x: batch_x, y: batch_y, current_batch_size: batch_current_batch_size}) # train on the given batch size of features and labels
total_cost += batch_cost
print("Epoch:", epoch, "\tCost:", total_cost)
# predict validation accuracy after every epoch
sum_accuracy_validation = 0.0
sum_i = 0
for i in range(0, int(dataset_validation_features.shape[0]/BATCH_SIZE)):
batch_x, batch_current_batch_size = get_batch(dataset_validation_features, i, BATCH_SIZE)
batch_y, _ = get_batch(dataset_validation_labels, i, BATCH_SIZE)
# print(batch_current_batch_size)
y_predicted = tf.nn.softmax(logits)
correct = tf.equal(tf.argmax(y_predicted, 1), tf.argmax(y, 1))
accuracy_function = tf.reduce_mean(tf.cast(correct, 'float'))
accuracy_validation = accuracy_function.eval({x:batch_x, y:batch_y, current_batch_size:batch_current_batch_size})
sum_accuracy_validation += accuracy_validation
sum_i += 1
print("Validation Accuracy in Epoch ", epoch, ":", accuracy_validation, 'sum_i:', sum_i, 'sum_accuracy_validation:', sum_accuracy_validation)
# training end
# testing
if epoch > 0 and epoch%2 == 0:
y_predicted_labels = []
audio_files_list = []
dataset_test_features = []
test_samples_picked = 0
y_predicted = tf.nn.softmax(logits)
for audio_file in audio_filenames:
audio_files_list.append(audio_file)
dataset_test_features.append(get_audio_test_dataset_features_labels(DATASET_PATH, audio_file))
if len(audio_files_list) == 3200:
dataset_test_features = np.array(dataset_test_features)
dataset_test_features = normalize_test_dataset(dataset_test_features, min_value, max_value)
for i in range(0, int(dataset_test_features.shape[0]/BATCH_SIZE)):
batch_x, batch_current_batch_size = get_batch(dataset_test_features, i, BATCH_SIZE)
temp = sess.run(tf.argmax(y_predicted, 1), feed_dict={x: batch_x, current_batch_size: batch_current_batch_size})
for element in temp:
y_predicted_labels.append(element)
test_samples_picked += 3200
print('test_samples_picked:', test_samples_picked)
# writing predicted labels into a csv file
with open('run'+str(epoch)+'.csv','a') as file:
for i in range(0, len(y_predicted_labels)):
file.write(str(audio_files_list[i]) + ',' + str(ALLOWED_LABELS_MAP[str(int(y_predicted_labels[i]))]))
file.write('\n')
y_predicted_labels = []
dataset_test_features = []
audio_files_list = []
# last set
dataset_test_features = np.array(dataset_test_features)
dataset_test_features = normalize_test_dataset(dataset_test_features, min_value, max_value)
for i in range(0, int(dataset_test_features.shape[0]/BATCH_SIZE)):
batch_x, batch_current_batch_size = get_batch(dataset_test_features, i, BATCH_SIZE)
temp = sess.run(tf.argmax(y_predicted, 1), feed_dict={x: batch_x, current_batch_size: batch_current_batch_size})
for element in temp:
y_predicted_labels.append(element)
test_samples_picked += 3200
print('test_samples_picked:', test_samples_picked)
# writing predicted labels into a csv file
with open('run'+str(epoch)+'.csv','a') as file:
for i in range(0, len(y_predicted_labels)):
file.write(str(audio_files_list[i]) + ',' + str(ALLOWED_LABELS_MAP[str(int(y_predicted_labels[i]))]))
file.write('\n')
| [
"random.shuffle",
"tensorflow.reshape",
"data_preprocessing.normalize_test_dataset",
"data_preprocessing.get_audio_test_dataset_filenames",
"tensorflow.matmul",
"tensorflow.nn.softmax",
"tensorflow.nn.softmax_cross_entropy_with_logits",
"tensorflow.placeholder",
"tensorflow.cast",
"data_preprocess... | [((1209, 1286), 'data_preprocessing.get_audio_dataset_features_labels', 'get_audio_dataset_features_labels', (['DATASET_PATH', 'ALLOWED_LABELS'], {'type': '"""train"""'}), "(DATASET_PATH, ALLOWED_LABELS, type='train')\n", (1242, 1286), False, 'from data_preprocessing import get_audio_dataset_features_labels, get_audio_test_dataset_filenames, get_audio_test_dataset_features_labels, normalize_training_dataset, normalize_test_dataset\n'), ((1305, 1351), 'data_preprocessing.get_audio_test_dataset_filenames', 'get_audio_test_dataset_filenames', (['DATASET_PATH'], {}), '(DATASET_PATH)\n', (1337, 1351), False, 'from data_preprocessing import get_audio_dataset_features_labels, get_audio_test_dataset_filenames, get_audio_test_dataset_features_labels, normalize_training_dataset, normalize_test_dataset\n'), ((1609, 1659), 'data_preprocessing.normalize_training_dataset', 'normalize_training_dataset', (['dataset_train_features'], {}), '(dataset_train_features)\n', (1635, 1659), False, 'from data_preprocessing import get_audio_dataset_features_labels, get_audio_test_dataset_filenames, get_audio_test_dataset_features_labels, normalize_training_dataset, normalize_test_dataset\n'), ((2647, 2711), 'tensorflow.placeholder', 'tf.placeholder', (['tf.float32'], {'shape': '[None, NUM_CHUNKS, CHUNK_SIZE]'}), '(tf.float32, shape=[None, NUM_CHUNKS, CHUNK_SIZE])\n', (2661, 2711), True, 'import tensorflow as tf\n'), ((2716, 2769), 'tensorflow.placeholder', 'tf.placeholder', (['tf.float32'], {'shape': '[None, NUM_CLASSES]'}), '(tf.float32, shape=[None, NUM_CLASSES])\n', (2730, 2769), True, 'import tensorflow as tf\n'), ((2791, 2815), 'tensorflow.placeholder', 'tf.placeholder', (['tf.int32'], {}), '(tf.int32)\n', (2805, 2815), True, 'import tensorflow as tf\n'), ((3911, 3935), 'tensorflow.train.AdamOptimizer', 'tf.train.AdamOptimizer', ([], {}), '()\n', (3933, 3935), True, 'import tensorflow as tf\n'), ((447, 479), 'random.shuffle', 'random.shuffle', (['dataset_combined'], {}), '(dataset_combined)\n', (461, 479), False, 'import random\n'), ((2886, 2924), 'tensorflow.contrib.rnn.LSTMCell', 'rnn.LSTMCell', (['(128)'], {'state_is_tuple': '(True)'}), '(128, state_is_tuple=True)\n', (2898, 2924), False, 'from tensorflow.contrib import rnn\n'), ((2940, 2978), 'tensorflow.contrib.rnn.LSTMCell', 'rnn.LSTMCell', (['(256)'], {'state_is_tuple': '(True)'}), '(256, state_is_tuple=True)\n', (2952, 2978), False, 'from tensorflow.contrib import rnn\n'), ((2994, 3032), 'tensorflow.contrib.rnn.LSTMCell', 'rnn.LSTMCell', (['(384)'], {'state_is_tuple': '(True)'}), '(384, state_is_tuple=True)\n', (3006, 3032), False, 'from tensorflow.contrib import rnn\n'), ((3053, 3131), 'tensorflow.contrib.rnn.MultiRNNCell', 'rnn.MultiRNNCell', (['[lstm_cell_1, lstm_cell_2, lstm_cell_3]'], {'state_is_tuple': '(True)'}), '([lstm_cell_1, lstm_cell_2, lstm_cell_3], state_is_tuple=True)\n', (3069, 3131), False, 'from tensorflow.contrib import rnn\n'), ((3170, 3226), 'tensorflow.nn.dynamic_rnn', 'tf.nn.dynamic_rnn', (['multi_lstm_cells', 'x'], {'dtype': 'tf.float32'}), '(multi_lstm_cells, x, dtype=tf.float32)\n', (3187, 3226), True, 'import tensorflow as tf\n'), ((3243, 3284), 'tensorflow.reshape', 'tf.reshape', (['lstm_layer_1', '[-1, 161 * 384]'], {}), '(lstm_layer_1, [-1, 161 * 384])\n', (3253, 3284), True, 'import tensorflow as tf\n'), ((3833, 3897), 'tensorflow.nn.softmax_cross_entropy_with_logits', 'tf.nn.softmax_cross_entropy_with_logits', ([], {'logits': 'logits', 'labels': 'y'}), '(logits=logits, labels=y)\n', (3872, 3897), True, 'import tensorflow as tf\n'), ((3978, 3990), 'tensorflow.Session', 'tf.Session', ([], {}), '()\n', (3988, 3990), True, 'import tensorflow as tf\n'), ((3309, 3343), 'tensorflow.random_normal', 'tf.random_normal', (['[161 * 384, 128]'], {}), '([161 * 384, 128])\n', (3325, 3343), True, 'import tensorflow as tf\n'), ((3386, 3422), 'tensorflow.random_normal', 'tf.random_normal', (['[128, NUM_CLASSES]'], {}), '([128, NUM_CLASSES])\n', (3402, 3422), True, 'import tensorflow as tf\n'), ((3466, 3489), 'tensorflow.random_normal', 'tf.random_normal', (['[128]'], {}), '([128])\n', (3482, 3489), True, 'import tensorflow as tf\n'), ((3533, 3564), 'tensorflow.random_normal', 'tf.random_normal', (['[NUM_CLASSES]'], {}), '([NUM_CLASSES])\n', (3549, 3564), True, 'import tensorflow as tf\n'), ((3606, 3640), 'tensorflow.matmul', 'tf.matmul', (['lstm_layer_1', 'weights_1'], {}), '(lstm_layer_1, weights_1)\n', (3615, 3640), True, 'import tensorflow as tf\n'), ((3673, 3712), 'tensorflow.matmul', 'tf.matmul', (['fully_connected_1', 'weights_2'], {}), '(fully_connected_1, weights_2)\n', (3682, 3712), True, 'import tensorflow as tf\n'), ((4010, 4043), 'tensorflow.global_variables_initializer', 'tf.global_variables_initializer', ([], {}), '()\n', (4041, 4043), True, 'import tensorflow as tf\n'), ((5121, 5142), 'tensorflow.nn.softmax', 'tf.nn.softmax', (['logits'], {}), '(logits)\n', (5134, 5142), True, 'import tensorflow as tf\n'), ((5790, 5811), 'tensorflow.nn.softmax', 'tf.nn.softmax', (['logits'], {}), '(logits)\n', (5803, 5811), True, 'import tensorflow as tf\n'), ((7046, 7077), 'numpy.array', 'np.array', (['dataset_test_features'], {}), '(dataset_test_features)\n', (7054, 7077), True, 'import numpy as np\n'), ((7105, 7172), 'data_preprocessing.normalize_test_dataset', 'normalize_test_dataset', (['dataset_test_features', 'min_value', 'max_value'], {}), '(dataset_test_features, min_value, max_value)\n', (7127, 7172), False, 'from data_preprocessing import get_audio_dataset_features_labels, get_audio_test_dataset_filenames, get_audio_test_dataset_features_labels, normalize_training_dataset, normalize_test_dataset\n'), ((5165, 5190), 'tensorflow.argmax', 'tf.argmax', (['y_predicted', '(1)'], {}), '(y_predicted, 1)\n', (5174, 5190), True, 'import tensorflow as tf\n'), ((5192, 5207), 'tensorflow.argmax', 'tf.argmax', (['y', '(1)'], {}), '(y, 1)\n', (5201, 5207), True, 'import tensorflow as tf\n'), ((5247, 5272), 'tensorflow.cast', 'tf.cast', (['correct', '"""float"""'], {}), "(correct, 'float')\n", (5254, 5272), True, 'import tensorflow as tf\n'), ((5924, 5988), 'data_preprocessing.get_audio_test_dataset_features_labels', 'get_audio_test_dataset_features_labels', (['DATASET_PATH', 'audio_file'], {}), '(DATASET_PATH, audio_file)\n', (5962, 5988), False, 'from data_preprocessing import get_audio_dataset_features_labels, get_audio_test_dataset_filenames, get_audio_test_dataset_features_labels, normalize_training_dataset, normalize_test_dataset\n'), ((6058, 6089), 'numpy.array', 'np.array', (['dataset_test_features'], {}), '(dataset_test_features)\n', (6066, 6089), True, 'import numpy as np\n'), ((6119, 6186), 'data_preprocessing.normalize_test_dataset', 'normalize_test_dataset', (['dataset_test_features', 'min_value', 'max_value'], {}), '(dataset_test_features, min_value, max_value)\n', (6141, 6186), False, 'from data_preprocessing import get_audio_dataset_features_labels, get_audio_test_dataset_filenames, get_audio_test_dataset_features_labels, normalize_training_dataset, normalize_test_dataset\n'), ((7352, 7377), 'tensorflow.argmax', 'tf.argmax', (['y_predicted', '(1)'], {}), '(y_predicted, 1)\n', (7361, 7377), True, 'import tensorflow as tf\n'), ((6372, 6397), 'tensorflow.argmax', 'tf.argmax', (['y_predicted', '(1)'], {}), '(y_predicted, 1)\n', (6381, 6397), True, 'import tensorflow as tf\n')] |
import pytest
import numpy as np
from utils import check_q
@pytest.mark.kuka
def test_kuka_kr6_r900(n_attempts):
from ikfast_kuka_kr6_r900 import get_fk, get_ik, get_dof, get_free_dof
print('*****************\n KUKA_KR6_R900 ikfast_pybind test')
n_jts = get_dof()
n_free_jts = get_free_dof()
assert n_jts == 6 and n_free_jts == 0
print('kuka_kr6_r900: \nn_jts: {}, n_free_jts: {}'.format(n_jts, n_free_jts))
# Test forward kinematics: get end effector pose from joint angles
print("Testing forward kinematics:")
given_jt_conf = [0.08, -1.57, 1.74, 0.08, 0.17, -0.08] # in radians
pos, rot = get_fk(given_jt_conf)
print('jt_conf: {}'.format(given_jt_conf))
print('ee pos: {}, rot: {}'.format(pos, rot))
# https://github.com/ros-industrial/kuka_experimental/blob/indigo-devel/kuka_kr6_support/urdf/kr6r900sixx_macro.xacro
feasible_ranges = {'robot_joint_1' : {'lower' : -np.radians(170), 'upper' : np.radians(170)},
'robot_joint_2' : {'lower' : -np.radians(190), 'upper' : np.radians(45)},
'robot_joint_3' : {'lower' : -np.radians(120), 'upper' : np.radians(156)},
'robot_joint_4' : {'lower' : -np.radians(185), 'upper' : np.radians(185)},
'robot_joint_5' : {'lower' : -np.radians(120), 'upper' : np.radians(120)},
'robot_joint_6' : {'lower' : -np.radians(350), 'upper' : np.radians(350)},
}
print("Testing random configurations...")
for _ in range(n_attempts):
q = np.random.rand(n_jts)
for i, jt_name in enumerate(feasible_ranges.keys()):
q[i] = q[i] * (feasible_ranges[jt_name]['upper'] - feasible_ranges[jt_name]['lower']) + \
feasible_ranges[jt_name]['lower']
check_q(get_fk, get_ik, q, feasible_ranges)
print("Done!")
| [
"numpy.radians",
"ikfast_kuka_kr6_r900.get_free_dof",
"ikfast_kuka_kr6_r900.get_dof",
"ikfast_kuka_kr6_r900.get_fk",
"utils.check_q",
"numpy.random.rand"
] | [((267, 276), 'ikfast_kuka_kr6_r900.get_dof', 'get_dof', ([], {}), '()\n', (274, 276), False, 'from ikfast_kuka_kr6_r900 import get_fk, get_ik, get_dof, get_free_dof\n'), ((294, 308), 'ikfast_kuka_kr6_r900.get_free_dof', 'get_free_dof', ([], {}), '()\n', (306, 308), False, 'from ikfast_kuka_kr6_r900 import get_fk, get_ik, get_dof, get_free_dof\n'), ((633, 654), 'ikfast_kuka_kr6_r900.get_fk', 'get_fk', (['given_jt_conf'], {}), '(given_jt_conf)\n', (639, 654), False, 'from ikfast_kuka_kr6_r900 import get_fk, get_ik, get_dof, get_free_dof\n'), ((1584, 1605), 'numpy.random.rand', 'np.random.rand', (['n_jts'], {}), '(n_jts)\n', (1598, 1605), True, 'import numpy as np\n'), ((1838, 1881), 'utils.check_q', 'check_q', (['get_fk', 'get_ik', 'q', 'feasible_ranges'], {}), '(get_fk, get_ik, q, feasible_ranges)\n', (1845, 1881), False, 'from utils import check_q\n'), ((956, 971), 'numpy.radians', 'np.radians', (['(170)'], {}), '(170)\n', (966, 971), True, 'import numpy as np\n'), ((1056, 1070), 'numpy.radians', 'np.radians', (['(45)'], {}), '(45)\n', (1066, 1070), True, 'import numpy as np\n'), ((1154, 1169), 'numpy.radians', 'np.radians', (['(156)'], {}), '(156)\n', (1164, 1169), True, 'import numpy as np\n'), ((1253, 1268), 'numpy.radians', 'np.radians', (['(185)'], {}), '(185)\n', (1263, 1268), True, 'import numpy as np\n'), ((1352, 1367), 'numpy.radians', 'np.radians', (['(120)'], {}), '(120)\n', (1362, 1367), True, 'import numpy as np\n'), ((1451, 1466), 'numpy.radians', 'np.radians', (['(350)'], {}), '(350)\n', (1461, 1466), True, 'import numpy as np\n'), ((929, 944), 'numpy.radians', 'np.radians', (['(170)'], {}), '(170)\n', (939, 944), True, 'import numpy as np\n'), ((1029, 1044), 'numpy.radians', 'np.radians', (['(190)'], {}), '(190)\n', (1039, 1044), True, 'import numpy as np\n'), ((1127, 1142), 'numpy.radians', 'np.radians', (['(120)'], {}), '(120)\n', (1137, 1142), True, 'import numpy as np\n'), ((1226, 1241), 'numpy.radians', 'np.radians', (['(185)'], {}), '(185)\n', (1236, 1241), True, 'import numpy as np\n'), ((1325, 1340), 'numpy.radians', 'np.radians', (['(120)'], {}), '(120)\n', (1335, 1340), True, 'import numpy as np\n'), ((1424, 1439), 'numpy.radians', 'np.radians', (['(350)'], {}), '(350)\n', (1434, 1439), True, 'import numpy as np\n')] |
#
# Author: <NAME>
#
import sys
import unittest
import numpy as np
from scipy.spatial.distance import cityblock
from machine_learning.neighbours import kNN
data = np.ndarray([[1, 1], [2, 3], [4, 2]])
labels = np.ndarray(['a', 'a', 'b'])
class kNNTest(unittest.TestCase):
def setUp(self):
self.knn = kNN(data, labels, cityblock, 1)
""" Constructor input parameter test """
def test_data(self):
with self.assertRaises(ValueError):
knn = kNN(np.array([]), labels, cityblock, 1)
def test_labels_empty(self):
with self.assertRaises(ValueError):
knn = kNN(data, np.array([]), cityblock, 1)
def test_labels_length(self):
with self.assertRaises(ValueError):
knn = kNN(data, np.array(['a', 'a']), cityblock, 1)
def test_distance(self):
with self.assertRaises(ValueError):
knn = kNN(data, labels, "cityblock", 1)
def test_leafsize(self):
with self.assertRaises(ValueError):
knn = kNN(data, labels, cityblock, 0)
""" Find kNN parameter test """
def test_invalid_k(self):
with self.assertRaises(ValueError):
self.knn.find_knn(0, np.ndarray([2, 2]))
def test_invalid_k_(self):
with self.assertRaises(ValueError):
self.knn.find_knn(data.shape[1]+1, np.ndarray([2, 2]))
def test_point_shape(self):
with self.assertRaises(ValueError):
self.knn.find_knn(1, np.ndarray([2, 2, 2]))
""" Setter input parameter test """
def test_data_setter(self):
with self.assertRaises(ValueError):
self.knn.data = np.array([])
def test_labels_setter_empty(self):
with self.assertRaises(ValueError):
self.knn.labels = np.array([])
def test_labels_setter_length(self):
with self.assertRaises(ValueError):
self.knn.labels = np.array(['a', 'a'])
def test_distance_setter(self):
with self.assertRaises(ValueError):
self.knn.distance = "cityblock"
def test_leafsize_setter(self):
with self.assertRaises(ValueError):
self.knn.leafsize = 0
if __name__ == "__main__":
unittest.main() | [
"unittest.main",
"numpy.ndarray",
"numpy.array",
"machine_learning.neighbours.kNN"
] | [((167, 203), 'numpy.ndarray', 'np.ndarray', (['[[1, 1], [2, 3], [4, 2]]'], {}), '([[1, 1], [2, 3], [4, 2]])\n', (177, 203), True, 'import numpy as np\n'), ((213, 240), 'numpy.ndarray', 'np.ndarray', (["['a', 'a', 'b']"], {}), "(['a', 'a', 'b'])\n", (223, 240), True, 'import numpy as np\n'), ((2187, 2202), 'unittest.main', 'unittest.main', ([], {}), '()\n', (2200, 2202), False, 'import unittest\n'), ((317, 348), 'machine_learning.neighbours.kNN', 'kNN', (['data', 'labels', 'cityblock', '(1)'], {}), '(data, labels, cityblock, 1)\n', (320, 348), False, 'from machine_learning.neighbours import kNN\n'), ((892, 925), 'machine_learning.neighbours.kNN', 'kNN', (['data', 'labels', '"""cityblock"""', '(1)'], {}), "(data, labels, 'cityblock', 1)\n", (895, 925), False, 'from machine_learning.neighbours import kNN\n'), ((1018, 1049), 'machine_learning.neighbours.kNN', 'kNN', (['data', 'labels', 'cityblock', '(0)'], {}), '(data, labels, cityblock, 0)\n', (1021, 1049), False, 'from machine_learning.neighbours import kNN\n'), ((1637, 1649), 'numpy.array', 'np.array', (['[]'], {}), '([])\n', (1645, 1649), True, 'import numpy as np\n'), ((1765, 1777), 'numpy.array', 'np.array', (['[]'], {}), '([])\n', (1773, 1777), True, 'import numpy as np\n'), ((1894, 1914), 'numpy.array', 'np.array', (["['a', 'a']"], {}), "(['a', 'a'])\n", (1902, 1914), True, 'import numpy as np\n'), ((487, 499), 'numpy.array', 'np.array', (['[]'], {}), '([])\n', (495, 499), True, 'import numpy as np\n'), ((629, 641), 'numpy.array', 'np.array', (['[]'], {}), '([])\n', (637, 641), True, 'import numpy as np\n'), ((764, 784), 'numpy.array', 'np.array', (["['a', 'a']"], {}), "(['a', 'a'])\n", (772, 784), True, 'import numpy as np\n'), ((1195, 1213), 'numpy.ndarray', 'np.ndarray', (['[2, 2]'], {}), '([2, 2])\n', (1205, 1213), True, 'import numpy as np\n'), ((1338, 1356), 'numpy.ndarray', 'np.ndarray', (['[2, 2]'], {}), '([2, 2])\n', (1348, 1356), True, 'import numpy as np\n'), ((1468, 1489), 'numpy.ndarray', 'np.ndarray', (['[2, 2, 2]'], {}), '([2, 2, 2])\n', (1478, 1489), True, 'import numpy as np\n')] |
#!/usr/bin/env python
# Copyright (c) 2011, <NAME>, Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
# * Neither the name of the <NAME>, Inc. nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
# cmd1.data=from 0 to 180
# cmd2.data=from 0 to 255
# cmd3.data=1 CW
# cmd3.data=2 CCW
# cmd3.data=0 brake
# cmd3.data=3 cut off power
# servo 0 is at right and 180 is at left
import rospy
import numpy as np
from std_msgs.msg import UInt8
from geometry_msgs.msg import Twist
if __name__=="__main__":
cmd1 = UInt8()
cmd2 = UInt8()
cmd3 = UInt8()
def callback(msg):
cmd1.data = msg.angular.z*180.0/np.pi+90
cmd2.data = abs(msg.linear.x) * 100
cmd3.data = 2-np.sign(msg.linear.x)
rospy.init_node('arduino_test')
pub1 = rospy.Publisher('servoCmd', UInt8, queue_size=1)
pub2 = rospy.Publisher('motorSpdCmd', UInt8, queue_size=1)
pub3 = rospy.Publisher('motorModeCmd', UInt8, queue_size=1)
rospy.Subscriber("/turtlebot_teleop/cmd_vel", Twist, callback)
rate = rospy.Rate(20)
def _shutdown():
cmd1.data = 90
cmd2.data = 0
cmd3.data = 0
pub1.publish(cmd1)
pub2.publish(cmd2)
pub3.publish(cmd3)
rospy.on_shutdown(_shutdown)
while not rospy.is_shutdown():
pub1.publish(cmd1)
pub2.publish(cmd2)
pub3.publish(cmd3)
rate.sleep()
| [
"rospy.Subscriber",
"rospy.Publisher",
"rospy.Rate",
"rospy.on_shutdown",
"rospy.is_shutdown",
"rospy.init_node",
"numpy.sign",
"std_msgs.msg.UInt8"
] | [((1895, 1902), 'std_msgs.msg.UInt8', 'UInt8', ([], {}), '()\n', (1900, 1902), False, 'from std_msgs.msg import UInt8\n'), ((1914, 1921), 'std_msgs.msg.UInt8', 'UInt8', ([], {}), '()\n', (1919, 1921), False, 'from std_msgs.msg import UInt8\n'), ((1933, 1940), 'std_msgs.msg.UInt8', 'UInt8', ([], {}), '()\n', (1938, 1940), False, 'from std_msgs.msg import UInt8\n'), ((2107, 2138), 'rospy.init_node', 'rospy.init_node', (['"""arduino_test"""'], {}), "('arduino_test')\n", (2122, 2138), False, 'import rospy\n'), ((2150, 2198), 'rospy.Publisher', 'rospy.Publisher', (['"""servoCmd"""', 'UInt8'], {'queue_size': '(1)'}), "('servoCmd', UInt8, queue_size=1)\n", (2165, 2198), False, 'import rospy\n'), ((2210, 2261), 'rospy.Publisher', 'rospy.Publisher', (['"""motorSpdCmd"""', 'UInt8'], {'queue_size': '(1)'}), "('motorSpdCmd', UInt8, queue_size=1)\n", (2225, 2261), False, 'import rospy\n'), ((2273, 2325), 'rospy.Publisher', 'rospy.Publisher', (['"""motorModeCmd"""', 'UInt8'], {'queue_size': '(1)'}), "('motorModeCmd', UInt8, queue_size=1)\n", (2288, 2325), False, 'import rospy\n'), ((2330, 2392), 'rospy.Subscriber', 'rospy.Subscriber', (['"""/turtlebot_teleop/cmd_vel"""', 'Twist', 'callback'], {}), "('/turtlebot_teleop/cmd_vel', Twist, callback)\n", (2346, 2392), False, 'import rospy\n'), ((2404, 2418), 'rospy.Rate', 'rospy.Rate', (['(20)'], {}), '(20)\n', (2414, 2418), False, 'import rospy\n'), ((2594, 2622), 'rospy.on_shutdown', 'rospy.on_shutdown', (['_shutdown'], {}), '(_shutdown)\n', (2611, 2622), False, 'import rospy\n'), ((2645, 2664), 'rospy.is_shutdown', 'rospy.is_shutdown', ([], {}), '()\n', (2662, 2664), False, 'import rospy\n'), ((2080, 2101), 'numpy.sign', 'np.sign', (['msg.linear.x'], {}), '(msg.linear.x)\n', (2087, 2101), True, 'import numpy as np\n')] |
import redisAI
import numpy as np
from concurrent.futures import ThreadPoolExecutor
executor = None
def execute_model(i, transaction_tensor, reference_tensor):
modelRunner = redisAI.createModelRunner('model_'+str(i))
redisAI.modelRunnerAddInput(modelRunner, 'transaction', transaction_tensor)
redisAI.modelRunnerAddInput(modelRunner, 'reference', reference_tensor)
redisAI.modelRunnerAddOutput(modelRunner, 'output')
model_replies = redisAI.modelRunnerRun(modelRunner)
return model_replies[0]
def parallel_models(x):
global executor
transaction_ndarray = np.random.randn(1, 30).astype(np.float32)
reference_ndarray = np.random.randn(1, 256).astype(np.float32)
transaction_tensor = redisAI.createTensorFromBlob('FLOAT', transaction_ndarray.shape,
transaction_ndarray.tobytes())
reference_tensor = redisAI.createTensorFromBlob('FLOAT', reference_ndarray.shape,
reference_ndarray.tobytes())
models_reply = [None]*2
for i in range(2):
models_reply[i] = executor.submit(execute_model, i, transaction_tensor, reference_tensor)
reply_tensor_0 = models_reply[0].result()
reply_tensor_1 = models_reply[1].result()
# reply_tensor_0 = execute_model (transaction_tensor, reference_tensor)
# reply_tensor_1 = execute_model (transaction_tensor, reference_tensor)
shape = redisAI.tensorGetDims(reply_tensor_0)
reply_ndarray_0 = np.frombuffer(redisAI.tensorGetDataAsBlob(reply_tensor_0), dtype=np.float32).reshape(shape)
reply_ndarray_1 = np.frombuffer(redisAI.tensorGetDataAsBlob(reply_tensor_1), dtype=np.float32).reshape(shape)
# reply_ndarray_1 = np.empty((1,2))
res = (reply_ndarray_0 + reply_ndarray_1) / 2.0
return (res[0][0]+res[0][1])
def init():
global executor
executor = ThreadPoolExecutor()
gb = GB('CommandReader')
gb.map(parallel_models)
gb.register(trigger='parallel_models', onRegistered=init)
| [
"redisAI.tensorGetDims",
"redisAI.tensorGetDataAsBlob",
"numpy.random.randn",
"redisAI.modelRunnerAddInput",
"redisAI.modelRunnerRun",
"redisAI.modelRunnerAddOutput",
"concurrent.futures.ThreadPoolExecutor"
] | [((228, 303), 'redisAI.modelRunnerAddInput', 'redisAI.modelRunnerAddInput', (['modelRunner', '"""transaction"""', 'transaction_tensor'], {}), "(modelRunner, 'transaction', transaction_tensor)\n", (255, 303), False, 'import redisAI\n'), ((308, 379), 'redisAI.modelRunnerAddInput', 'redisAI.modelRunnerAddInput', (['modelRunner', '"""reference"""', 'reference_tensor'], {}), "(modelRunner, 'reference', reference_tensor)\n", (335, 379), False, 'import redisAI\n'), ((384, 435), 'redisAI.modelRunnerAddOutput', 'redisAI.modelRunnerAddOutput', (['modelRunner', '"""output"""'], {}), "(modelRunner, 'output')\n", (412, 435), False, 'import redisAI\n'), ((456, 491), 'redisAI.modelRunnerRun', 'redisAI.modelRunnerRun', (['modelRunner'], {}), '(modelRunner)\n', (478, 491), False, 'import redisAI\n'), ((1448, 1485), 'redisAI.tensorGetDims', 'redisAI.tensorGetDims', (['reply_tensor_0'], {}), '(reply_tensor_0)\n', (1469, 1485), False, 'import redisAI\n'), ((1888, 1908), 'concurrent.futures.ThreadPoolExecutor', 'ThreadPoolExecutor', ([], {}), '()\n', (1906, 1908), False, 'from concurrent.futures import ThreadPoolExecutor\n'), ((591, 613), 'numpy.random.randn', 'np.random.randn', (['(1)', '(30)'], {}), '(1, 30)\n', (606, 613), True, 'import numpy as np\n'), ((657, 680), 'numpy.random.randn', 'np.random.randn', (['(1)', '(256)'], {}), '(1, 256)\n', (672, 680), True, 'import numpy as np\n'), ((1522, 1565), 'redisAI.tensorGetDataAsBlob', 'redisAI.tensorGetDataAsBlob', (['reply_tensor_0'], {}), '(reply_tensor_0)\n', (1549, 1565), False, 'import redisAI\n'), ((1636, 1679), 'redisAI.tensorGetDataAsBlob', 'redisAI.tensorGetDataAsBlob', (['reply_tensor_1'], {}), '(reply_tensor_1)\n', (1663, 1679), False, 'import redisAI\n')] |
# Copyright 2019 The Vearch Authors. 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.
# ==============================================================================
import cv2
import numpy as np
from PIL import Image
import torch
from torchvision import transforms
import torchvision.models as models
import torch.nn.functional as F
class BaseModel(object):
def __init__(self):
self.image_size = 224
self.dimision = 512
def load_model(self):
self.device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
self.model = models.alexnet(pretrained=True).to(self.device)
self.model = self.model.eval()
self.PIXEL_MEANS = torch.tensor((0.485, 0.456, 0.406)).to(self.device)
self.PIXEL_STDS = torch.tensor((0.229, 0.224, 0.225)).to(self.device)
self.num = torch.tensor(255.0).to(self.device)
def preprocess_input(self, image):
image = cv2.resize(image, (self.image_size, self.image_size))
# gpu version
image_tensor = torch.from_numpy(image.copy()).to(self.device).float()
image_tensor /= self.num
image_tensor -= self.PIXEL_MEANS
image_tensor /= self.PIXEL_STDS
image_tensor = image_tensor.permute(2, 0 ,1)
return image_tensor
def forward(self, x):
# x = torch.stack(x)
# x = x.to(self.device)
x = self.preprocess_input(x).unsqueeze(0)
x = self.model.features(x)
x = F.max_pool2d(x, kernel_size=(7, 7))
x = x.view(x.size(0),-1)
# print(x.shape)
# x = torch.squeeze(x,-1)
# x = torch.squeeze(x,-1)
return self.torch2list(x)
def torch2list(self, torch_data):
return torch_data.cpu().detach().numpy().tolist()
def load_model():
return BaseModel()
def test():
model = load_model()
model.load_model()
import urllib.request
def test_url(imageurl):
resp = urllib.request.urlopen(imageurl).read()
image = np.asarray(bytearray(resp), dtype="uint8")
image = cv2.imdecode(image, cv2.IMREAD_COLOR)
feat = model.forward(image)
return feat[0]/np.linalg.norm(feat[0])
print(test_url("http://img30.360buyimg.com/da/jfs/t14458/111/1073427178/210435/20d7f66/5a436349Ncf9bea13.jpg"))
# from PIL import Image
# image1 = cv2.imread("../../images/test/COCO_val2014_000000123599.jpg")
# # image2 = cv2.imread("../../images/test/COCO_val2014_000000123599.jpg")
# print(model.forward(image1[:,:,::-1]))
# import time
# start = time.time()
# tensor1 = model.preprocess_input(image1)
# tensor2 = model.preprocess_input2(image1)
# print(time.time()-start)
# data = [tensor1,tensor2]
# data = [tensor1]
# data = torch.stack([tensor1,tensor2])
# print(data.shape)
# array1,array2 = model.forward(data)
# import keras_vgg16 as kv
# keras_model = kv.model
# image2 = image1[:,:,::-1]
# image2 = cv2.resize(image2, (224, 224))
# image2 = image2[np.newaxis,:]
# image2 = keras_model.preprocess_input(image2)
# array2 = keras_model.predict(image2)[0]
# image2 = image2.transpose(0,3,1,2)
# array1 = model.forward(model.preprocess_input(image2))[0]
# print(np.array(array1).shape, np.array(array2).shape)
# print(np.dot(array1, array2)/(np.linalg.norm(array1) * np.linalg.norm(array2)))
if __name__ == "__main__":
test()
| [
"cv2.imdecode",
"torchvision.models.alexnet",
"torch.cuda.is_available",
"numpy.linalg.norm",
"torch.nn.functional.max_pool2d",
"torch.tensor",
"cv2.resize"
] | [((1343, 1396), 'cv2.resize', 'cv2.resize', (['image', '(self.image_size, self.image_size)'], {}), '(image, (self.image_size, self.image_size))\n', (1353, 1396), False, 'import cv2\n'), ((1877, 1912), 'torch.nn.functional.max_pool2d', 'F.max_pool2d', (['x'], {'kernel_size': '(7, 7)'}), '(x, kernel_size=(7, 7))\n', (1889, 1912), True, 'import torch.nn.functional as F\n'), ((2457, 2494), 'cv2.imdecode', 'cv2.imdecode', (['image', 'cv2.IMREAD_COLOR'], {}), '(image, cv2.IMREAD_COLOR)\n', (2469, 2494), False, 'import cv2\n'), ((2554, 2577), 'numpy.linalg.norm', 'np.linalg.norm', (['feat[0]'], {}), '(feat[0])\n', (2568, 2577), True, 'import numpy as np\n'), ((929, 954), 'torch.cuda.is_available', 'torch.cuda.is_available', ([], {}), '()\n', (952, 954), False, 'import torch\n'), ((988, 1019), 'torchvision.models.alexnet', 'models.alexnet', ([], {'pretrained': '(True)'}), '(pretrained=True)\n', (1002, 1019), True, 'import torchvision.models as models\n'), ((1102, 1137), 'torch.tensor', 'torch.tensor', (['(0.485, 0.456, 0.406)'], {}), '((0.485, 0.456, 0.406))\n', (1114, 1137), False, 'import torch\n'), ((1180, 1215), 'torch.tensor', 'torch.tensor', (['(0.229, 0.224, 0.225)'], {}), '((0.229, 0.224, 0.225))\n', (1192, 1215), False, 'import torch\n'), ((1251, 1270), 'torch.tensor', 'torch.tensor', (['(255.0)'], {}), '(255.0)\n', (1263, 1270), False, 'import torch\n')] |
# Copyright 2021 Google Inc. 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.
"""Tests accuracy and correct TF1 usage for grad_cam."""
import unittest
import unittest.mock as mock
from . import grad_cam
import numpy as np
import tensorflow.compat.v1 as tf
INPUT_HEIGHT_WIDTH = 5 # width and height of input images in pixels
class GradCamTest(unittest.TestCase):
"""To run: "python -m saliency.tf1.grad_cam_test" from top-level saliency directory."""
def setUp(self):
super().setUp()
self.graph = tf.Graph()
with self.graph.as_default():
# Input placeholder
self.images = tf.placeholder(
tf.float32, shape=(1, INPUT_HEIGHT_WIDTH, INPUT_HEIGHT_WIDTH, 1))
# Horizontal line detector filter
horiz_detector = np.array([[-1, -1, -1],
[2, 2, 2],
[-1, -1, -1]])
conv1 = tf.keras.layers.Conv2D(
filters=1,
kernel_size=3,
kernel_initializer=tf.constant_initializer(horiz_detector),
padding='same',
name='Conv',
input_shape=self.images.shape)(self.images)
# Compute logits and do prediction with pre-defined weights
flat = tf.reshape(conv1, [-1, INPUT_HEIGHT_WIDTH*INPUT_HEIGHT_WIDTH])
sum_weights = tf.constant_initializer(np.ones(flat.shape))
logits = tf.keras.layers.Dense(
units=2, kernel_initializer=sum_weights, name='Logits')(flat)
y = logits[0][0]
self.sess = tf.Session()
init = tf.global_variables_initializer()
self.sess.run(init)
self.sess_spy = mock.MagicMock(wraps=self.sess)
# Set up GradCam object
self.conv_layer = self.graph.get_tensor_by_name('Conv/BiasAdd:0')
self.grad_cam_instance = grad_cam.GradCam(self.graph,
self.sess_spy,
y=y,
x=self.images,
conv_layer=self.conv_layer)
def testGradCamGetMask(self):
"""Tests the GradCAM method using a simple network.
Simple test case where the network contains one convolutional layer that
acts as a horizontal line detector and the input image is a 5x5 matrix with
a centered 3x3 grid of 1s and 0s elsewhere.
The computed GradCAM mask should detect the pixels of highest importance to
be along the two horizontal lines in the image (exact expected values stored
in ref_mask).
"""
# Generate test input (centered matrix of 1s surrounded by 0s)
# and generate corresponding GradCAM mask
img = np.zeros([INPUT_HEIGHT_WIDTH, INPUT_HEIGHT_WIDTH])
img[1:-1, 1:-1] = 1
img = img.reshape([INPUT_HEIGHT_WIDTH, INPUT_HEIGHT_WIDTH, 1])
mask = self.grad_cam_instance.GetMask(
img,
feed_dict={},
should_resize=True,
three_dims=False)
# Compare generated mask to expected result
ref_mask = np.array([[0., 0., 0., 0., 0.],
[0.33, 0.67, 1., 0.67, 0.33],
[0., 0., 0., 0., 0.],
[0.33, 0.67, 1., 0.67, 0.33],
[0., 0., 0., 0., 0.]])
self.assertTrue(np.allclose(mask, ref_mask, atol=0.01),
'Generated mask did not match reference mask.')
def testGradCamGetMaskArgs(self):
"""Tests that sess.run receives the correct inputs."""
img = np.ones([INPUT_HEIGHT_WIDTH, INPUT_HEIGHT_WIDTH])
img = img.reshape([INPUT_HEIGHT_WIDTH, INPUT_HEIGHT_WIDTH, 1])
feed_dict = {'foo': 'bar'}
self.sess_spy.run.return_value = [[img], [img]]
self.grad_cam_instance.GetMask(
img, feed_dict=feed_dict, should_resize=True, three_dims=False)
actual_feed_dict = self.sess_spy.run.call_args[1]['feed_dict']
self.assertEqual(actual_feed_dict['foo'], feed_dict['foo'])
if __name__ == '__main__':
unittest.main()
| [
"unittest.main",
"unittest.mock.MagicMock",
"tensorflow.compat.v1.placeholder",
"numpy.allclose",
"numpy.zeros",
"numpy.ones",
"tensorflow.compat.v1.global_variables_initializer",
"tensorflow.compat.v1.keras.layers.Dense",
"tensorflow.compat.v1.constant_initializer",
"tensorflow.compat.v1.Session"... | [((4465, 4480), 'unittest.main', 'unittest.main', ([], {}), '()\n', (4478, 4480), False, 'import unittest\n'), ((1033, 1043), 'tensorflow.compat.v1.Graph', 'tf.Graph', ([], {}), '()\n', (1041, 1043), True, 'import tensorflow.compat.v1 as tf\n'), ((3184, 3234), 'numpy.zeros', 'np.zeros', (['[INPUT_HEIGHT_WIDTH, INPUT_HEIGHT_WIDTH]'], {}), '([INPUT_HEIGHT_WIDTH, INPUT_HEIGHT_WIDTH])\n', (3192, 3234), True, 'import numpy as np\n'), ((3522, 3684), 'numpy.array', 'np.array', (['[[0.0, 0.0, 0.0, 0.0, 0.0], [0.33, 0.67, 1.0, 0.67, 0.33], [0.0, 0.0, 0.0, \n 0.0, 0.0], [0.33, 0.67, 1.0, 0.67, 0.33], [0.0, 0.0, 0.0, 0.0, 0.0]]'], {}), '([[0.0, 0.0, 0.0, 0.0, 0.0], [0.33, 0.67, 1.0, 0.67, 0.33], [0.0, \n 0.0, 0.0, 0.0, 0.0], [0.33, 0.67, 1.0, 0.67, 0.33], [0.0, 0.0, 0.0, 0.0,\n 0.0]])\n', (3530, 3684), True, 'import numpy as np\n'), ((3993, 4042), 'numpy.ones', 'np.ones', (['[INPUT_HEIGHT_WIDTH, INPUT_HEIGHT_WIDTH]'], {}), '([INPUT_HEIGHT_WIDTH, INPUT_HEIGHT_WIDTH])\n', (4000, 4042), True, 'import numpy as np\n'), ((1124, 1209), 'tensorflow.compat.v1.placeholder', 'tf.placeholder', (['tf.float32'], {'shape': '(1, INPUT_HEIGHT_WIDTH, INPUT_HEIGHT_WIDTH, 1)'}), '(tf.float32, shape=(1, INPUT_HEIGHT_WIDTH, INPUT_HEIGHT_WIDTH, 1)\n )\n', (1138, 1209), True, 'import tensorflow.compat.v1 as tf\n'), ((1280, 1329), 'numpy.array', 'np.array', (['[[-1, -1, -1], [2, 2, 2], [-1, -1, -1]]'], {}), '([[-1, -1, -1], [2, 2, 2], [-1, -1, -1]])\n', (1288, 1329), True, 'import numpy as np\n'), ((1733, 1797), 'tensorflow.compat.v1.reshape', 'tf.reshape', (['conv1', '[-1, INPUT_HEIGHT_WIDTH * INPUT_HEIGHT_WIDTH]'], {}), '(conv1, [-1, INPUT_HEIGHT_WIDTH * INPUT_HEIGHT_WIDTH])\n', (1743, 1797), True, 'import tensorflow.compat.v1 as tf\n'), ((2019, 2031), 'tensorflow.compat.v1.Session', 'tf.Session', ([], {}), '()\n', (2029, 2031), True, 'import tensorflow.compat.v1 as tf\n'), ((2045, 2078), 'tensorflow.compat.v1.global_variables_initializer', 'tf.global_variables_initializer', ([], {}), '()\n', (2076, 2078), True, 'import tensorflow.compat.v1 as tf\n'), ((2127, 2158), 'unittest.mock.MagicMock', 'mock.MagicMock', ([], {'wraps': 'self.sess'}), '(wraps=self.sess)\n', (2141, 2158), True, 'import unittest.mock as mock\n'), ((3779, 3817), 'numpy.allclose', 'np.allclose', (['mask', 'ref_mask'], {'atol': '(0.01)'}), '(mask, ref_mask, atol=0.01)\n', (3790, 3817), True, 'import numpy as np\n'), ((1840, 1859), 'numpy.ones', 'np.ones', (['flat.shape'], {}), '(flat.shape)\n', (1847, 1859), True, 'import numpy as np\n'), ((1876, 1953), 'tensorflow.compat.v1.keras.layers.Dense', 'tf.keras.layers.Dense', ([], {'units': '(2)', 'kernel_initializer': 'sum_weights', 'name': '"""Logits"""'}), "(units=2, kernel_initializer=sum_weights, name='Logits')\n", (1897, 1953), True, 'import tensorflow.compat.v1 as tf\n'), ((1509, 1548), 'tensorflow.compat.v1.constant_initializer', 'tf.constant_initializer', (['horiz_detector'], {}), '(horiz_detector)\n', (1532, 1548), True, 'import tensorflow.compat.v1 as tf\n')] |
import numpy as np
def results_updated_nobatchnorm():
accs = np.array([[[(33.52, (0, 0)), (35.4, (0, 10)), (38.14, (0, 20)), (38.98, (0, 30)), (41.08, (0, 40)),
(43.26, (0, 50)), (43.98, (0, 60)), (42.84, (0, 70)), (43.56, (0, 80)), (43.66, (0, 90)),
(45.5, (1, 0)), (47.26, (2, 0)), (50.36, (3, 0)), (50.48, (4, 0)), (48.84, (5, 0)),
(52.4, (6, 0)), (52.08, (7, 0)), (51.8, (8, 0)), (51.52, (9, 0))],
[(29.62, (0, 0)), (36.22, (0, 10)), (35.34, (0, 20)), (36.76, (0, 30)), (38.66, (0, 40)),
(40.58, (0, 50)), (41.78, (0, 60)), (43.2, (0, 70)), (44.62, (0, 80)), (44.52, (0, 90)),
(45.44, (1, 0)), (48.0, (2, 0)), (48.86, (3, 0)), (51.52, (4, 0)), (52.74, (5, 0)),
(53.12, (6, 0)), (52.62, (7, 0)), (54.48, (8, 0)), (52.6, (9, 0))],
[(30.18, (0, 0)), (37.56, (0, 10)), (36.74, (0, 20)), (38.3, (0, 30)), (40.12, (0, 40)),
(39.06, (0, 50)), (42.04, (0, 60)), (43.3, (0, 70)), (44.24, (0, 80)), (44.44, (0, 90)),
(45.98, (1, 0)), (48.0, (2, 0)), (51.56, (3, 0)), (51.2, (4, 0)), (50.92, (5, 0)),
(50.74, (6, 0)), (51.2, (7, 0)), (52.96, (8, 0)), (53.36, (9, 0))]],
[[(26.36, (0, 0)), (32.08, (0, 10)), (34.42, (0, 20)), (34.36, (0, 30)), (32.94, (0, 40)),
(34.72, (0, 50)), (35.34, (0, 60)), (34.18, (0, 70)), (34.1, (0, 80)), (33.66, (0, 90)),
(37.48, (1, 0)), (39.92, (2, 0)), (42.0, (3, 0)), (38.72, (4, 0)), (43.04, (5, 0)),
(44.48, (6, 0)), (44.48, (7, 0)), (47.02, (8, 0)), (46.06, (9, 0))],
[(27.12, (0, 0)), (36.58, (0, 10)), (38.8, (0, 20)), (41.76, (0, 30)), (40.54, (0, 40)),
(41.76, (0, 50)), (43.6, (0, 60)), (43.0, (0, 70)), (42.12, (0, 80)), (40.44, (0, 90)),
(42.38, (1, 0)), (42.28, (2, 0)), (44.96, (3, 0)), (49.76, (4, 0)), (49.84, (5, 0)),
(49.0, (6, 0)), (50.2, (7, 0)), (48.76, (8, 0)), (50.8, (9, 0))],
[(29.06, (0, 0)), (33.22, (0, 10)), (36.0, (0, 20)), (36.76, (0, 30)), (37.4, (0, 40)),
(39.6, (0, 50)), (39.68, (0, 60)), (38.64, (0, 70)), (40.22, (0, 80)), (39.42, (0, 90)),
(40.14, (1, 0)), (43.54, (2, 0)), (44.66, (3, 0)), (44.94, (4, 0)), (45.3, (5, 0)),
(46.64, (6, 0)), (48.76, (7, 0)), (48.96, (8, 0)), (48.38, (9, 0))]],
[[(40.5, (0, 0)), (45.86, (0, 10)), (48.76, (0, 20)), (48.46, (0, 30)), (50.06, (0, 40)),
(51.18, (0, 50)), (50.06, (0, 60)), (52.2, (0, 70)), (53.34, (0, 80)), (53.78, (0, 90)),
(52.96, (1, 0)), (55.66, (2, 0)), (56.4, (3, 0)), (56.84, (4, 0)), (59.12, (5, 0)),
(58.04, (6, 0)), (59.28, (7, 0)), (59.16, (8, 0)), (59.84, (9, 0))],
[(41.18, (0, 0)), (44.64, (0, 10)), (47.16, (0, 20)), (48.18, (0, 30)), (49.38, (0, 40)),
(49.98, (0, 50)), (51.36, (0, 60)), (52.22, (0, 70)), (52.92, (0, 80)), (52.64, (0, 90)),
(52.6, (1, 0)), (55.8, (2, 0)), (57.04, (3, 0)), (56.04, (4, 0)), (57.8, (5, 0)),
(57.86, (6, 0)), (58.36, (7, 0)), (59.08, (8, 0)), (60.14, (9, 0))],
[(41.24, (0, 0)), (46.0, (0, 10)), (47.22, (0, 20)), (48.58, (0, 30)), (49.84, (0, 40)),
(49.8, (0, 50)), (50.46, (0, 60)), (50.54, (0, 70)), (52.28, (0, 80)), (52.52, (0, 90)),
(53.02, (1, 0)), (56.38, (2, 0)), (55.62, (3, 0)), (57.32, (4, 0)), (57.48, (5, 0)),
(58.84, (6, 0)), (58.74, (7, 0)), (57.62, (8, 0)), (59.54, (9, 0))]],
[[(31.04, (0, 0)), (41.64, (0, 10)), (42.98, (0, 20)), (43.8, (0, 30)), (45.44, (0, 40)),
(46.28, (0, 50)), (46.68, (0, 60)), (48.82, (0, 70)), (49.18, (0, 80)), (49.0, (0, 90)),
(49.02, (1, 0)), (52.04, (2, 0)), (53.84, (3, 0)), (54.84, (4, 0)), (56.62, (5, 0)),
(55.88, (6, 0)), (56.92, (7, 0)), (56.62, (8, 0)), (56.74, (9, 0))],
[(30.74, (0, 0)), (39.6, (0, 10)), (43.1, (0, 20)), (45.14, (0, 30)), (46.14, (0, 40)),
(46.92, (0, 50)), (49.06, (0, 60)), (50.4, (0, 70)), (49.98, (0, 80)), (50.06, (0, 90)),
(49.76, (1, 0)), (52.16, (2, 0)), (53.48, (3, 0)), (54.82, (4, 0)), (56.12, (5, 0)),
(56.96, (6, 0)), (57.08, (7, 0)), (59.0, (8, 0)), (58.34, (9, 0))],
[(31.86, (0, 0)), (38.46, (0, 10)), (40.12, (0, 20)), (42.12, (0, 30)), (43.44, (0, 40)),
(44.94, (0, 50)), (46.18, (0, 60)), (47.12, (0, 70)), (47.44, (0, 80)), (47.84, (0, 90)),
(48.74, (1, 0)), (53.06, (2, 0)), (54.24, (3, 0)), (53.92, (4, 0)), (54.74, (5, 0)),
(55.78, (6, 0)), (56.6, (7, 0)), (56.42, (8, 0)), (57.78, (9, 0))]],
[[(26.66, (0, 0)), (29.1, (0, 10)), (32.36, (0, 20)), (35.52, (0, 30)), (36.12, (0, 40)),
(38.46, (0, 50)), (35.6, (0, 60)), (35.28, (0, 70)), (35.9, (0, 80)), (36.64, (0, 90)),
(35.58, (1, 0)), (39.14, (2, 0)), (40.26, (3, 0)), (43.18, (4, 0)), (45.36, (5, 0)),
(44.1, (6, 0)), (43.08, (7, 0)), (46.08, (8, 0)), (44.92, (9, 0))],
[(29.44, (0, 0)), (31.36, (0, 10)), (28.82, (0, 20)), (30.66, (0, 30)), (33.82, (0, 40)),
(32.3, (0, 50)), (32.52, (0, 60)), (32.92, (0, 70)), (32.8, (0, 80)), (34.64, (0, 90)),
(33.22, (1, 0)), (40.02, (2, 0)), (43.92, (3, 0)), (42.34, (4, 0)), (41.24, (5, 0)),
(42.72, (6, 0)), (39.82, (7, 0)), (42.48, (8, 0)), (38.7, (9, 0))],
[(26.58, (0, 0)), (25.94, (0, 10)), (32.48, (0, 20)), (28.42, (0, 30)), (26.9, (0, 40)),
(30.4, (0, 50)), (30.02, (0, 60)), (30.48, (0, 70)), (31.54, (0, 80)), (32.96, (0, 90)),
(32.22, (1, 0)), (35.8, (2, 0)), (35.3, (3, 0)), (35.18, (4, 0)), (35.94, (5, 0)),
(32.72, (6, 0)), (29.96, (7, 0)), (34.08, (8, 0)), (33.02, (9, 0))]],
[[(28.98, (0, 0)), (27.82, (0, 10)), (28.48, (0, 20)), (28.72, (0, 30)), (26.12, (0, 40)),
(25.14, (0, 50)), (24.82, (0, 60)), (24.8, (0, 70)), (24.72, (0, 80)), (24.24, (0, 90)),
(24.28, (1, 0)), (25.84, (2, 0)), (25.66, (3, 0)), (26.04, (4, 0)), (26.54, (5, 0)),
(29.72, (6, 0)), (28.08, (7, 0)), (29.44, (8, 0)), (28.48, (9, 0))],
[(25.16, (0, 0)), (29.64, (0, 10)), (30.92, (0, 20)), (27.22, (0, 30)), (28.9, (0, 40)),
(28.24, (0, 50)), (26.7, (0, 60)), (28.92, (0, 70)), (29.8, (0, 80)), (30.66, (0, 90)),
(33.16, (1, 0)), (33.64, (2, 0)), (35.58, (3, 0)), (33.18, (4, 0)), (35.06, (5, 0)),
(35.26, (6, 0)), (35.26, (7, 0)), (40.08, (8, 0)), (34.76, (9, 0))],
[(24.9, (0, 0)), (28.9, (0, 10)), (27.06, (0, 20)), (21.16, (0, 30)), (22.18, (0, 40)),
(24.3, (0, 50)), (21.4, (0, 60)), (20.6, (0, 70)), (20.5, (0, 80)), (20.62, (0, 90)),
(20.7, (1, 0)), (22.94, (2, 0)), (26.92, (3, 0)), (29.04, (4, 0)), (28.76, (5, 0)),
(26.34, (6, 0)), (27.32, (7, 0)), (26.4, (8, 0)), (33.54, (9, 0))]]])
widths = np.array([16, 8, 512, 32, 4, 2])
order = widths.argsort()
widths.sort()
sorted_accs = accs[order]
return widths, sorted_accs
# ResNet-18, 5 classes, 25,000 images, 100 linear probing epochs, classical, variable bottleneck, sigmoid before
# testnet, batchnorm before sigmoid
def results_updated():
accs = np.array([[[(26.62, (0, 0)), (36.98, (0, 10)), (37.24, (0, 20)), (33.96, (0, 30)), (38.6, (0, 40)),
(37.58, (0, 50)), (34.84, (0, 60)), (33.14, (0, 70)), (36.48, (0, 80)), (39.88, (0, 90)),
(46.42, (1, 0)), (48.9, (2, 0)), (50.02, (3, 0)), (51.38, (4, 0)), (51.82, (5, 0)),
(51.04, (6, 0)), (51.32, (7, 0)), (50.78, (8, 0)), (53.98, (9, 0))],
[(31.02, (0, 0)), (37.02, (0, 10)), (38.12, (0, 20)), (39.04, (0, 30)), (41.32, (0, 40)),
(43.06, (0, 50)), (42.68, (0, 60)), (43.52, (0, 70)), (43.16, (0, 80)), (44.16, (0, 90)),
(45.48, (1, 0)), (48.8, (2, 0)), (49.62, (3, 0)), (51.94, (4, 0)), (52.74, (5, 0)),
(52.34, (6, 0)), (53.98, (7, 0)), (54.4, (8, 0)), (55.66, (9, 0))],
[(31.4, (0, 0)), (38.42, (0, 10)), (38.96, (0, 20)), (40.42, (0, 30)), (42.34, (0, 40)),
(42.54, (0, 50)), (43.52, (0, 60)), (44.2, (0, 70)), (46.4, (0, 80)), (45.92, (0, 90)),
(46.84, (1, 0)), (48.7, (2, 0)), (49.34, (3, 0)), (51.22, (4, 0)), (52.5, (5, 0)),
(53.86, (6, 0)), (54.6, (7, 0)), (53.94, (8, 0)), (55.1, (9, 0))]],
[[(31.16, (0, 0)), (35.84, (0, 10)), (34.28, (0, 20)), (32.74, (0, 30)), (35.14, (0, 40)),
(36.24, (0, 50)), (36.76, (0, 60)), (36.62, (0, 70)), (22.6, (0, 80)), (30.56, (0, 90)),
(38.22, (1, 0)), (44.24, (2, 0)), (46.46, (3, 0)), (46.7, (4, 0)), (48.12, (5, 0)),
(49.18, (6, 0)), (47.68, (7, 0)), (51.2, (8, 0)), (48.18, (9, 0))],
[(30.4, (0, 0)), (32.96, (0, 10)), (35.56, (0, 20)), (39.16, (0, 30)), (39.52, (0, 40)),
(40.1, (0, 50)), (39.78, (0, 60)), (39.94, (0, 70)), (40.78, (0, 80)), (41.08, (0, 90)),
(42.02, (1, 0)), (44.78, (2, 0)), (45.62, (3, 0)), (46.82, (4, 0)), (46.76, (5, 0)),
(49.34, (6, 0)), (49.72, (7, 0)), (49.9, (8, 0)), (51.46, (9, 0))],
[(29.14, (0, 0)), (31.28, (0, 10)), (33.06, (0, 20)), (32.94, (0, 30)), (34.04, (0, 40)),
(33.58, (0, 50)), (34.3, (0, 60)), (35.04, (0, 70)), (35.7, (0, 80)), (37.46, (0, 90)),
(37.36, (1, 0)), (41.9, (2, 0)), (45.22, (3, 0)), (42.9, (4, 0)), (43.38, (5, 0)),
(44.5, (6, 0)), (45.14, (7, 0)), (46.84, (8, 0)), (48.38, (9, 0))]],
[[(40.64, (0, 0)), (47.1, (0, 10)), (49.92, (0, 20)), (49.44, (0, 30)), (50.34, (0, 40)),
(50.04, (0, 50)), (51.74, (0, 60)), (52.76, (0, 70)), (52.68, (0, 80)), (53.58, (0, 90)),
(52.98, (1, 0)), (53.26, (2, 0)), (56.24, (3, 0)), (56.82, (4, 0)), (58.14, (5, 0)),
(58.52, (6, 0)), (58.98, (7, 0)), (58.94, (8, 0)), (59.86, (9, 0))],
[(41.58, (0, 0)), (46.48, (0, 10)), (47.92, (0, 20)), (50.06, (0, 30)), (50.14, (0, 40)),
(51.46, (0, 50)), (51.9, (0, 60)), (51.72, (0, 70)), (52.28, (0, 80)), (53.14, (0, 90)),
(53.72, (1, 0)), (56.16, (2, 0)), (55.8, (3, 0)), (56.62, (4, 0)), (57.0, (5, 0)),
(57.18, (6, 0)), (58.38, (7, 0)), (57.72, (8, 0)), (59.48, (9, 0))],
[(38.64, (0, 0)), (44.78, (0, 10)), (48.06, (0, 20)), (49.98, (0, 30)), (51.24, (0, 40)),
(51.74, (0, 50)), (52.98, (0, 60)), (52.9, (0, 70)), (53.32, (0, 80)), (53.58, (0, 90)),
(53.64, (1, 0)), (55.78, (2, 0)), (56.0, (3, 0)), (56.8, (4, 0)), (57.82, (5, 0)),
(58.48, (6, 0)), (59.02, (7, 0)), (59.48, (8, 0)), (60.04, (9, 0))]],
[[(32.08, (0, 0)), (40.42, (0, 10)), (42.78, (0, 20)), (44.3, (0, 30)), (45.2, (0, 40)),
(46.54, (0, 50)), (47.38, (0, 60)), (48.72, (0, 70)), (49.76, (0, 80)), (50.26, (0, 90)),
(50.82, (1, 0)), (52.58, (2, 0)), (53.1, (3, 0)), (53.72, (4, 0)), (54.38, (5, 0)),
(55.82, (6, 0)), (56.16, (7, 0)), (56.82, (8, 0)), (56.32, (9, 0))],
[(32.16, (0, 0)), (38.64, (0, 10)), (41.44, (0, 20)), (43.32, (0, 30)), (45.16, (0, 40)),
(46.6, (0, 50)), (47.62, (0, 60)), (48.66, (0, 70)), (48.04, (0, 80)), (49.1, (0, 90)),
(47.78, (1, 0)), (51.42, (2, 0)), (53.5, (3, 0)), (54.44, (4, 0)), (55.06, (5, 0)),
(56.06, (6, 0)), (55.5, (7, 0)), (55.92, (8, 0)), (57.0, (9, 0))],
[(34.0, (0, 0)), (38.46, (0, 10)), (43.88, (0, 20)), (45.98, (0, 30)), (46.84, (0, 40)),
(47.86, (0, 50)), (48.6, (0, 60)), (48.88, (0, 70)), (49.5, (0, 80)), (49.52, (0, 90)),
(49.88, (1, 0)), (51.24, (2, 0)), (52.22, (3, 0)), (54.4, (4, 0)), (54.84, (5, 0)),
(55.24, (6, 0)), (56.74, (7, 0)), (57.36, (8, 0)), (55.98, (9, 0))]],
[[(24.04, (0, 0)), (30.7, (0, 10)), (31.46, (0, 20)), (31.62, (0, 30)), (32.96, (0, 40)),
(33.66, (0, 50)), (36.06, (0, 60)), (34.78, (0, 70)), (34.44, (0, 80)), (36.38, (0, 90)),
(36.14, (1, 0)), (42.62, (2, 0)), (42.96, (3, 0)), (44.54, (4, 0)), (45.38, (5, 0)),
(45.94, (6, 0)), (46.06, (7, 0)), (45.78, (8, 0)), (48.06, (9, 0))],
[(31.68, (0, 0)), (31.64, (0, 10)), (30.6, (0, 20)), (31.94, (0, 30)), (32.92, (0, 40)),
(30.6, (0, 50)), (34.02, (0, 60)), (33.92, (0, 70)), (33.52, (0, 80)), (35.34, (0, 90)),
(34.38, (1, 0)), (39.56, (2, 0)), (39.24, (3, 0)), (39.56, (4, 0)), (42.12, (5, 0)),
(41.6, (6, 0)), (41.14, (7, 0)), (41.08, (8, 0)), (40.64, (9, 0))],
[(26.1, (0, 0)), (31.14, (0, 10)), (31.94, (0, 20)), (32.54, (0, 30)), (31.2, (0, 40)),
(32.7, (0, 50)), (32.48, (0, 60)), (33.32, (0, 70)), (33.16, (0, 80)), (32.9, (0, 90)),
(33.2, (1, 0)), (34.26, (2, 0)), (36.5, (3, 0)), (35.46, (4, 0)), (36.38, (5, 0)),
(36.82, (6, 0)), (38.5, (7, 0)), (38.08, (8, 0)), (36.54, (9, 0))]],
[[(30.98, (0, 0)), (28.12, (0, 10)), (30.74, (0, 20)), (31.84, (0, 30)), (37.32, (0, 40)),
(35.24, (0, 50)), (37.64, (0, 60)), (39.76, (0, 70)), (38.4, (0, 80)), (37.0, (0, 90)),
(34.28, (1, 0)), (39.84, (2, 0)), (39.24, (3, 0)), (35.54, (4, 0)), (38.84, (5, 0)),
(38.24, (6, 0)), (39.64, (7, 0)), (39.56, (8, 0)), (39.18, (9, 0))],
[(28.58, (0, 0)), (27.88, (0, 10)), (26.44, (0, 20)), (29.62, (0, 30)), (30.08, (0, 40)),
(33.2, (0, 50)), (32.54, (0, 60)), (32.0, (0, 70)), (33.42, (0, 80)), (33.24, (0, 90)),
(32.06, (1, 0)), (34.72, (2, 0)), (37.78, (3, 0)), (36.52, (4, 0)), (35.34, (5, 0)),
(35.88, (6, 0)), (35.78, (7, 0)), (33.82, (8, 0)), (33.92, (9, 0))],
[(22.04, (0, 0)), (27.34, (0, 10)), (26.34, (0, 20)), (23.58, (0, 30)), (22.72, (0, 40)),
(22.04, (0, 50)), (20.76, (0, 60)), (20.8, (0, 70)), (20.7, (0, 80)), (20.74, (0, 90)),
(20.74, (1, 0)), (20.7, (2, 0)), (20.58, (3, 0)), (21.24, (4, 0)), (20.68, (5, 0)),
(20.72, (6, 0)), (20.72, (7, 0)), (20.76, (8, 0)), (20.7, (9, 0))]]])
widths = np.array([16, 8, 512, 32, 4, 2])
order = widths.argsort()
widths.sort()
sorted_accs = accs[order]
return widths, sorted_accs
# ResNet-18, 5 classes, 25,000 images, 100 linear probing epochs, classical, variable bottleneck
def results():
accs = np.array([
[(33.22, 9), (37.56, 19), (27.46, 49), (31.48, 99), (35.3, 199), (36.76, 299)],
[(53.32, 9), (54.36, 19), (59.36, 49), (65.92, 99), (70.5, 199), (72.34, 299)],
[(45.0, 9), (46.76, 19), (51.0, 49), (37.92, 99), (41.7, 199), (43.46, 299)],
[(59.06, 9), (61.1, 19), (64.22, 49), (67.64, 99), (70.18, 199), (71.64, 299)],
[(52.56, 9), (55.16, 19), (60.88, 49), (62.08, 99), (63.56, 199), (64.02, 299)],
[(56.84, 9), (57.9, 19), (60.82, 49), (66.88, 99), (68.14, 199), (70.58, 299)],
[(61.1, 9), (62.88, 19), (62.2, 49), (64.22, 99), (68.14, 199), (70.04, 299)]])
widths = np.array([2, 12, 4, 32, 8, 16, 512])
order = widths.argsort()
widths.sort()
sorted_accs = accs[order]
return widths, sorted_accs
def results_identity():
accs = np.array([
[(38.64, 9), (39.04, 19), (40.1, 49), (42.48, 99), (42.66, 199), (39.58, 299)],
[(60.68, 9), (63.34, 19), (67.46, 49), (69.96, 99), (74.28, 199), (75.72, 299)],
[(58.88, 9), (61.44, 19), (64.58, 49), (68.78, 99), (70.36, 199), (72.16, 299)],
[(58.34, 9), (59.24, 19), (61.6, 49), (64.72, 99), (70.88, 199), (71.5, 299)],
[(51.14, 9), (51.92, 19), (51.32, 49), (52.94, 99), (53.18, 199), (54.18, 299)],
[(52.74, 9), (57.86, 19), (60.3, 49), (66.56, 99), (69.74, 199), (70.34, 299)],
[(64.76, 9), (68.42, 19), (72.32, 49), (75.66, 99), (78.48, 199), (80.12, 299)]
])
widths = np.array([2, 32, 16, 12, 4, 8, 512])
order = widths.argsort()
widths.sort()
sorted_accs = accs[order]
return widths, sorted_accs
| [
"numpy.array"
] | [((67, 6431), 'numpy.array', 'np.array', (['[[[(33.52, (0, 0)), (35.4, (0, 10)), (38.14, (0, 20)), (38.98, (0, 30)), (\n 41.08, (0, 40)), (43.26, (0, 50)), (43.98, (0, 60)), (42.84, (0, 70)),\n (43.56, (0, 80)), (43.66, (0, 90)), (45.5, (1, 0)), (47.26, (2, 0)), (\n 50.36, (3, 0)), (50.48, (4, 0)), (48.84, (5, 0)), (52.4, (6, 0)), (\n 52.08, (7, 0)), (51.8, (8, 0)), (51.52, (9, 0))], [(29.62, (0, 0)), (\n 36.22, (0, 10)), (35.34, (0, 20)), (36.76, (0, 30)), (38.66, (0, 40)),\n (40.58, (0, 50)), (41.78, (0, 60)), (43.2, (0, 70)), (44.62, (0, 80)),\n (44.52, (0, 90)), (45.44, (1, 0)), (48.0, (2, 0)), (48.86, (3, 0)), (\n 51.52, (4, 0)), (52.74, (5, 0)), (53.12, (6, 0)), (52.62, (7, 0)), (\n 54.48, (8, 0)), (52.6, (9, 0))], [(30.18, (0, 0)), (37.56, (0, 10)), (\n 36.74, (0, 20)), (38.3, (0, 30)), (40.12, (0, 40)), (39.06, (0, 50)), (\n 42.04, (0, 60)), (43.3, (0, 70)), (44.24, (0, 80)), (44.44, (0, 90)), (\n 45.98, (1, 0)), (48.0, (2, 0)), (51.56, (3, 0)), (51.2, (4, 0)), (50.92,\n (5, 0)), (50.74, (6, 0)), (51.2, (7, 0)), (52.96, (8, 0)), (53.36, (9, \n 0))]], [[(26.36, (0, 0)), (32.08, (0, 10)), (34.42, (0, 20)), (34.36, (\n 0, 30)), (32.94, (0, 40)), (34.72, (0, 50)), (35.34, (0, 60)), (34.18,\n (0, 70)), (34.1, (0, 80)), (33.66, (0, 90)), (37.48, (1, 0)), (39.92, (\n 2, 0)), (42.0, (3, 0)), (38.72, (4, 0)), (43.04, (5, 0)), (44.48, (6, 0\n )), (44.48, (7, 0)), (47.02, (8, 0)), (46.06, (9, 0))], [(27.12, (0, 0)\n ), (36.58, (0, 10)), (38.8, (0, 20)), (41.76, (0, 30)), (40.54, (0, 40)\n ), (41.76, (0, 50)), (43.6, (0, 60)), (43.0, (0, 70)), (42.12, (0, 80)),\n (40.44, (0, 90)), (42.38, (1, 0)), (42.28, (2, 0)), (44.96, (3, 0)), (\n 49.76, (4, 0)), (49.84, (5, 0)), (49.0, (6, 0)), (50.2, (7, 0)), (48.76,\n (8, 0)), (50.8, (9, 0))], [(29.06, (0, 0)), (33.22, (0, 10)), (36.0, (0,\n 20)), (36.76, (0, 30)), (37.4, (0, 40)), (39.6, (0, 50)), (39.68, (0, \n 60)), (38.64, (0, 70)), (40.22, (0, 80)), (39.42, (0, 90)), (40.14, (1,\n 0)), (43.54, (2, 0)), (44.66, (3, 0)), (44.94, (4, 0)), (45.3, (5, 0)),\n (46.64, (6, 0)), (48.76, (7, 0)), (48.96, (8, 0)), (48.38, (9, 0))]], [\n [(40.5, (0, 0)), (45.86, (0, 10)), (48.76, (0, 20)), (48.46, (0, 30)),\n (50.06, (0, 40)), (51.18, (0, 50)), (50.06, (0, 60)), (52.2, (0, 70)),\n (53.34, (0, 80)), (53.78, (0, 90)), (52.96, (1, 0)), (55.66, (2, 0)), (\n 56.4, (3, 0)), (56.84, (4, 0)), (59.12, (5, 0)), (58.04, (6, 0)), (\n 59.28, (7, 0)), (59.16, (8, 0)), (59.84, (9, 0))], [(41.18, (0, 0)), (\n 44.64, (0, 10)), (47.16, (0, 20)), (48.18, (0, 30)), (49.38, (0, 40)),\n (49.98, (0, 50)), (51.36, (0, 60)), (52.22, (0, 70)), (52.92, (0, 80)),\n (52.64, (0, 90)), (52.6, (1, 0)), (55.8, (2, 0)), (57.04, (3, 0)), (\n 56.04, (4, 0)), (57.8, (5, 0)), (57.86, (6, 0)), (58.36, (7, 0)), (\n 59.08, (8, 0)), (60.14, (9, 0))], [(41.24, (0, 0)), (46.0, (0, 10)), (\n 47.22, (0, 20)), (48.58, (0, 30)), (49.84, (0, 40)), (49.8, (0, 50)), (\n 50.46, (0, 60)), (50.54, (0, 70)), (52.28, (0, 80)), (52.52, (0, 90)),\n (53.02, (1, 0)), (56.38, (2, 0)), (55.62, (3, 0)), (57.32, (4, 0)), (\n 57.48, (5, 0)), (58.84, (6, 0)), (58.74, (7, 0)), (57.62, (8, 0)), (\n 59.54, (9, 0))]], [[(31.04, (0, 0)), (41.64, (0, 10)), (42.98, (0, 20)),\n (43.8, (0, 30)), (45.44, (0, 40)), (46.28, (0, 50)), (46.68, (0, 60)),\n (48.82, (0, 70)), (49.18, (0, 80)), (49.0, (0, 90)), (49.02, (1, 0)), (\n 52.04, (2, 0)), (53.84, (3, 0)), (54.84, (4, 0)), (56.62, (5, 0)), (\n 55.88, (6, 0)), (56.92, (7, 0)), (56.62, (8, 0)), (56.74, (9, 0))], [(\n 30.74, (0, 0)), (39.6, (0, 10)), (43.1, (0, 20)), (45.14, (0, 30)), (\n 46.14, (0, 40)), (46.92, (0, 50)), (49.06, (0, 60)), (50.4, (0, 70)), (\n 49.98, (0, 80)), (50.06, (0, 90)), (49.76, (1, 0)), (52.16, (2, 0)), (\n 53.48, (3, 0)), (54.82, (4, 0)), (56.12, (5, 0)), (56.96, (6, 0)), (\n 57.08, (7, 0)), (59.0, (8, 0)), (58.34, (9, 0))], [(31.86, (0, 0)), (\n 38.46, (0, 10)), (40.12, (0, 20)), (42.12, (0, 30)), (43.44, (0, 40)),\n (44.94, (0, 50)), (46.18, (0, 60)), (47.12, (0, 70)), (47.44, (0, 80)),\n (47.84, (0, 90)), (48.74, (1, 0)), (53.06, (2, 0)), (54.24, (3, 0)), (\n 53.92, (4, 0)), (54.74, (5, 0)), (55.78, (6, 0)), (56.6, (7, 0)), (\n 56.42, (8, 0)), (57.78, (9, 0))]], [[(26.66, (0, 0)), (29.1, (0, 10)),\n (32.36, (0, 20)), (35.52, (0, 30)), (36.12, (0, 40)), (38.46, (0, 50)),\n (35.6, (0, 60)), (35.28, (0, 70)), (35.9, (0, 80)), (36.64, (0, 90)), (\n 35.58, (1, 0)), (39.14, (2, 0)), (40.26, (3, 0)), (43.18, (4, 0)), (\n 45.36, (5, 0)), (44.1, (6, 0)), (43.08, (7, 0)), (46.08, (8, 0)), (\n 44.92, (9, 0))], [(29.44, (0, 0)), (31.36, (0, 10)), (28.82, (0, 20)),\n (30.66, (0, 30)), (33.82, (0, 40)), (32.3, (0, 50)), (32.52, (0, 60)),\n (32.92, (0, 70)), (32.8, (0, 80)), (34.64, (0, 90)), (33.22, (1, 0)), (\n 40.02, (2, 0)), (43.92, (3, 0)), (42.34, (4, 0)), (41.24, (5, 0)), (\n 42.72, (6, 0)), (39.82, (7, 0)), (42.48, (8, 0)), (38.7, (9, 0))], [(\n 26.58, (0, 0)), (25.94, (0, 10)), (32.48, (0, 20)), (28.42, (0, 30)), (\n 26.9, (0, 40)), (30.4, (0, 50)), (30.02, (0, 60)), (30.48, (0, 70)), (\n 31.54, (0, 80)), (32.96, (0, 90)), (32.22, (1, 0)), (35.8, (2, 0)), (\n 35.3, (3, 0)), (35.18, (4, 0)), (35.94, (5, 0)), (32.72, (6, 0)), (\n 29.96, (7, 0)), (34.08, (8, 0)), (33.02, (9, 0))]], [[(28.98, (0, 0)),\n (27.82, (0, 10)), (28.48, (0, 20)), (28.72, (0, 30)), (26.12, (0, 40)),\n (25.14, (0, 50)), (24.82, (0, 60)), (24.8, (0, 70)), (24.72, (0, 80)),\n (24.24, (0, 90)), (24.28, (1, 0)), (25.84, (2, 0)), (25.66, (3, 0)), (\n 26.04, (4, 0)), (26.54, (5, 0)), (29.72, (6, 0)), (28.08, (7, 0)), (\n 29.44, (8, 0)), (28.48, (9, 0))], [(25.16, (0, 0)), (29.64, (0, 10)), (\n 30.92, (0, 20)), (27.22, (0, 30)), (28.9, (0, 40)), (28.24, (0, 50)), (\n 26.7, (0, 60)), (28.92, (0, 70)), (29.8, (0, 80)), (30.66, (0, 90)), (\n 33.16, (1, 0)), (33.64, (2, 0)), (35.58, (3, 0)), (33.18, (4, 0)), (\n 35.06, (5, 0)), (35.26, (6, 0)), (35.26, (7, 0)), (40.08, (8, 0)), (\n 34.76, (9, 0))], [(24.9, (0, 0)), (28.9, (0, 10)), (27.06, (0, 20)), (\n 21.16, (0, 30)), (22.18, (0, 40)), (24.3, (0, 50)), (21.4, (0, 60)), (\n 20.6, (0, 70)), (20.5, (0, 80)), (20.62, (0, 90)), (20.7, (1, 0)), (\n 22.94, (2, 0)), (26.92, (3, 0)), (29.04, (4, 0)), (28.76, (5, 0)), (\n 26.34, (6, 0)), (27.32, (7, 0)), (26.4, (8, 0)), (33.54, (9, 0))]]]'], {}), '([[[(33.52, (0, 0)), (35.4, (0, 10)), (38.14, (0, 20)), (38.98, (0,\n 30)), (41.08, (0, 40)), (43.26, (0, 50)), (43.98, (0, 60)), (42.84, (0,\n 70)), (43.56, (0, 80)), (43.66, (0, 90)), (45.5, (1, 0)), (47.26, (2, 0\n )), (50.36, (3, 0)), (50.48, (4, 0)), (48.84, (5, 0)), (52.4, (6, 0)),\n (52.08, (7, 0)), (51.8, (8, 0)), (51.52, (9, 0))], [(29.62, (0, 0)), (\n 36.22, (0, 10)), (35.34, (0, 20)), (36.76, (0, 30)), (38.66, (0, 40)),\n (40.58, (0, 50)), (41.78, (0, 60)), (43.2, (0, 70)), (44.62, (0, 80)),\n (44.52, (0, 90)), (45.44, (1, 0)), (48.0, (2, 0)), (48.86, (3, 0)), (\n 51.52, (4, 0)), (52.74, (5, 0)), (53.12, (6, 0)), (52.62, (7, 0)), (\n 54.48, (8, 0)), (52.6, (9, 0))], [(30.18, (0, 0)), (37.56, (0, 10)), (\n 36.74, (0, 20)), (38.3, (0, 30)), (40.12, (0, 40)), (39.06, (0, 50)), (\n 42.04, (0, 60)), (43.3, (0, 70)), (44.24, (0, 80)), (44.44, (0, 90)), (\n 45.98, (1, 0)), (48.0, (2, 0)), (51.56, (3, 0)), (51.2, (4, 0)), (50.92,\n (5, 0)), (50.74, (6, 0)), (51.2, (7, 0)), (52.96, (8, 0)), (53.36, (9, \n 0))]], [[(26.36, (0, 0)), (32.08, (0, 10)), (34.42, (0, 20)), (34.36, (\n 0, 30)), (32.94, (0, 40)), (34.72, (0, 50)), (35.34, (0, 60)), (34.18,\n (0, 70)), (34.1, (0, 80)), (33.66, (0, 90)), (37.48, (1, 0)), (39.92, (\n 2, 0)), (42.0, (3, 0)), (38.72, (4, 0)), (43.04, (5, 0)), (44.48, (6, 0\n )), (44.48, (7, 0)), (47.02, (8, 0)), (46.06, (9, 0))], [(27.12, (0, 0)\n ), (36.58, (0, 10)), (38.8, (0, 20)), (41.76, (0, 30)), (40.54, (0, 40)\n ), (41.76, (0, 50)), (43.6, (0, 60)), (43.0, (0, 70)), (42.12, (0, 80)),\n (40.44, (0, 90)), (42.38, (1, 0)), (42.28, (2, 0)), (44.96, (3, 0)), (\n 49.76, (4, 0)), (49.84, (5, 0)), (49.0, (6, 0)), (50.2, (7, 0)), (48.76,\n (8, 0)), (50.8, (9, 0))], [(29.06, (0, 0)), (33.22, (0, 10)), (36.0, (0,\n 20)), (36.76, (0, 30)), (37.4, (0, 40)), (39.6, (0, 50)), (39.68, (0, \n 60)), (38.64, (0, 70)), (40.22, (0, 80)), (39.42, (0, 90)), (40.14, (1,\n 0)), (43.54, (2, 0)), (44.66, (3, 0)), (44.94, (4, 0)), (45.3, (5, 0)),\n (46.64, (6, 0)), (48.76, (7, 0)), (48.96, (8, 0)), (48.38, (9, 0))]], [\n [(40.5, (0, 0)), (45.86, (0, 10)), (48.76, (0, 20)), (48.46, (0, 30)),\n (50.06, (0, 40)), (51.18, (0, 50)), (50.06, (0, 60)), (52.2, (0, 70)),\n (53.34, (0, 80)), (53.78, (0, 90)), (52.96, (1, 0)), (55.66, (2, 0)), (\n 56.4, (3, 0)), (56.84, (4, 0)), (59.12, (5, 0)), (58.04, (6, 0)), (\n 59.28, (7, 0)), (59.16, (8, 0)), (59.84, (9, 0))], [(41.18, (0, 0)), (\n 44.64, (0, 10)), (47.16, (0, 20)), (48.18, (0, 30)), (49.38, (0, 40)),\n (49.98, (0, 50)), (51.36, (0, 60)), (52.22, (0, 70)), (52.92, (0, 80)),\n (52.64, (0, 90)), (52.6, (1, 0)), (55.8, (2, 0)), (57.04, (3, 0)), (\n 56.04, (4, 0)), (57.8, (5, 0)), (57.86, (6, 0)), (58.36, (7, 0)), (\n 59.08, (8, 0)), (60.14, (9, 0))], [(41.24, (0, 0)), (46.0, (0, 10)), (\n 47.22, (0, 20)), (48.58, (0, 30)), (49.84, (0, 40)), (49.8, (0, 50)), (\n 50.46, (0, 60)), (50.54, (0, 70)), (52.28, (0, 80)), (52.52, (0, 90)),\n (53.02, (1, 0)), (56.38, (2, 0)), (55.62, (3, 0)), (57.32, (4, 0)), (\n 57.48, (5, 0)), (58.84, (6, 0)), (58.74, (7, 0)), (57.62, (8, 0)), (\n 59.54, (9, 0))]], [[(31.04, (0, 0)), (41.64, (0, 10)), (42.98, (0, 20)),\n (43.8, (0, 30)), (45.44, (0, 40)), (46.28, (0, 50)), (46.68, (0, 60)),\n (48.82, (0, 70)), (49.18, (0, 80)), (49.0, (0, 90)), (49.02, (1, 0)), (\n 52.04, (2, 0)), (53.84, (3, 0)), (54.84, (4, 0)), (56.62, (5, 0)), (\n 55.88, (6, 0)), (56.92, (7, 0)), (56.62, (8, 0)), (56.74, (9, 0))], [(\n 30.74, (0, 0)), (39.6, (0, 10)), (43.1, (0, 20)), (45.14, (0, 30)), (\n 46.14, (0, 40)), (46.92, (0, 50)), (49.06, (0, 60)), (50.4, (0, 70)), (\n 49.98, (0, 80)), (50.06, (0, 90)), (49.76, (1, 0)), (52.16, (2, 0)), (\n 53.48, (3, 0)), (54.82, (4, 0)), (56.12, (5, 0)), (56.96, (6, 0)), (\n 57.08, (7, 0)), (59.0, (8, 0)), (58.34, (9, 0))], [(31.86, (0, 0)), (\n 38.46, (0, 10)), (40.12, (0, 20)), (42.12, (0, 30)), (43.44, (0, 40)),\n (44.94, (0, 50)), (46.18, (0, 60)), (47.12, (0, 70)), (47.44, (0, 80)),\n (47.84, (0, 90)), (48.74, (1, 0)), (53.06, (2, 0)), (54.24, (3, 0)), (\n 53.92, (4, 0)), (54.74, (5, 0)), (55.78, (6, 0)), (56.6, (7, 0)), (\n 56.42, (8, 0)), (57.78, (9, 0))]], [[(26.66, (0, 0)), (29.1, (0, 10)),\n (32.36, (0, 20)), (35.52, (0, 30)), (36.12, (0, 40)), (38.46, (0, 50)),\n (35.6, (0, 60)), (35.28, (0, 70)), (35.9, (0, 80)), (36.64, (0, 90)), (\n 35.58, (1, 0)), (39.14, (2, 0)), (40.26, (3, 0)), (43.18, (4, 0)), (\n 45.36, (5, 0)), (44.1, (6, 0)), (43.08, (7, 0)), (46.08, (8, 0)), (\n 44.92, (9, 0))], [(29.44, (0, 0)), (31.36, (0, 10)), (28.82, (0, 20)),\n (30.66, (0, 30)), (33.82, (0, 40)), (32.3, (0, 50)), (32.52, (0, 60)),\n (32.92, (0, 70)), (32.8, (0, 80)), (34.64, (0, 90)), (33.22, (1, 0)), (\n 40.02, (2, 0)), (43.92, (3, 0)), (42.34, (4, 0)), (41.24, (5, 0)), (\n 42.72, (6, 0)), (39.82, (7, 0)), (42.48, (8, 0)), (38.7, (9, 0))], [(\n 26.58, (0, 0)), (25.94, (0, 10)), (32.48, (0, 20)), (28.42, (0, 30)), (\n 26.9, (0, 40)), (30.4, (0, 50)), (30.02, (0, 60)), (30.48, (0, 70)), (\n 31.54, (0, 80)), (32.96, (0, 90)), (32.22, (1, 0)), (35.8, (2, 0)), (\n 35.3, (3, 0)), (35.18, (4, 0)), (35.94, (5, 0)), (32.72, (6, 0)), (\n 29.96, (7, 0)), (34.08, (8, 0)), (33.02, (9, 0))]], [[(28.98, (0, 0)),\n (27.82, (0, 10)), (28.48, (0, 20)), (28.72, (0, 30)), (26.12, (0, 40)),\n (25.14, (0, 50)), (24.82, (0, 60)), (24.8, (0, 70)), (24.72, (0, 80)),\n (24.24, (0, 90)), (24.28, (1, 0)), (25.84, (2, 0)), (25.66, (3, 0)), (\n 26.04, (4, 0)), (26.54, (5, 0)), (29.72, (6, 0)), (28.08, (7, 0)), (\n 29.44, (8, 0)), (28.48, (9, 0))], [(25.16, (0, 0)), (29.64, (0, 10)), (\n 30.92, (0, 20)), (27.22, (0, 30)), (28.9, (0, 40)), (28.24, (0, 50)), (\n 26.7, (0, 60)), (28.92, (0, 70)), (29.8, (0, 80)), (30.66, (0, 90)), (\n 33.16, (1, 0)), (33.64, (2, 0)), (35.58, (3, 0)), (33.18, (4, 0)), (\n 35.06, (5, 0)), (35.26, (6, 0)), (35.26, (7, 0)), (40.08, (8, 0)), (\n 34.76, (9, 0))], [(24.9, (0, 0)), (28.9, (0, 10)), (27.06, (0, 20)), (\n 21.16, (0, 30)), (22.18, (0, 40)), (24.3, (0, 50)), (21.4, (0, 60)), (\n 20.6, (0, 70)), (20.5, (0, 80)), (20.62, (0, 90)), (20.7, (1, 0)), (\n 22.94, (2, 0)), (26.92, (3, 0)), (29.04, (4, 0)), (28.76, (5, 0)), (\n 26.34, (6, 0)), (27.32, (7, 0)), (26.4, (8, 0)), (33.54, (9, 0))]]])\n', (75, 6431), True, 'import numpy as np\n'), ((7665, 7697), 'numpy.array', 'np.array', (['[16, 8, 512, 32, 4, 2]'], {}), '([16, 8, 512, 32, 4, 2])\n', (7673, 7697), True, 'import numpy as np\n'), ((7993, 14354), 'numpy.array', 'np.array', (['[[[(26.62, (0, 0)), (36.98, (0, 10)), (37.24, (0, 20)), (33.96, (0, 30)), (\n 38.6, (0, 40)), (37.58, (0, 50)), (34.84, (0, 60)), (33.14, (0, 70)), (\n 36.48, (0, 80)), (39.88, (0, 90)), (46.42, (1, 0)), (48.9, (2, 0)), (\n 50.02, (3, 0)), (51.38, (4, 0)), (51.82, (5, 0)), (51.04, (6, 0)), (\n 51.32, (7, 0)), (50.78, (8, 0)), (53.98, (9, 0))], [(31.02, (0, 0)), (\n 37.02, (0, 10)), (38.12, (0, 20)), (39.04, (0, 30)), (41.32, (0, 40)),\n (43.06, (0, 50)), (42.68, (0, 60)), (43.52, (0, 70)), (43.16, (0, 80)),\n (44.16, (0, 90)), (45.48, (1, 0)), (48.8, (2, 0)), (49.62, (3, 0)), (\n 51.94, (4, 0)), (52.74, (5, 0)), (52.34, (6, 0)), (53.98, (7, 0)), (\n 54.4, (8, 0)), (55.66, (9, 0))], [(31.4, (0, 0)), (38.42, (0, 10)), (\n 38.96, (0, 20)), (40.42, (0, 30)), (42.34, (0, 40)), (42.54, (0, 50)),\n (43.52, (0, 60)), (44.2, (0, 70)), (46.4, (0, 80)), (45.92, (0, 90)), (\n 46.84, (1, 0)), (48.7, (2, 0)), (49.34, (3, 0)), (51.22, (4, 0)), (52.5,\n (5, 0)), (53.86, (6, 0)), (54.6, (7, 0)), (53.94, (8, 0)), (55.1, (9, 0\n ))]], [[(31.16, (0, 0)), (35.84, (0, 10)), (34.28, (0, 20)), (32.74, (0,\n 30)), (35.14, (0, 40)), (36.24, (0, 50)), (36.76, (0, 60)), (36.62, (0,\n 70)), (22.6, (0, 80)), (30.56, (0, 90)), (38.22, (1, 0)), (44.24, (2, 0\n )), (46.46, (3, 0)), (46.7, (4, 0)), (48.12, (5, 0)), (49.18, (6, 0)),\n (47.68, (7, 0)), (51.2, (8, 0)), (48.18, (9, 0))], [(30.4, (0, 0)), (\n 32.96, (0, 10)), (35.56, (0, 20)), (39.16, (0, 30)), (39.52, (0, 40)),\n (40.1, (0, 50)), (39.78, (0, 60)), (39.94, (0, 70)), (40.78, (0, 80)),\n (41.08, (0, 90)), (42.02, (1, 0)), (44.78, (2, 0)), (45.62, (3, 0)), (\n 46.82, (4, 0)), (46.76, (5, 0)), (49.34, (6, 0)), (49.72, (7, 0)), (\n 49.9, (8, 0)), (51.46, (9, 0))], [(29.14, (0, 0)), (31.28, (0, 10)), (\n 33.06, (0, 20)), (32.94, (0, 30)), (34.04, (0, 40)), (33.58, (0, 50)),\n (34.3, (0, 60)), (35.04, (0, 70)), (35.7, (0, 80)), (37.46, (0, 90)), (\n 37.36, (1, 0)), (41.9, (2, 0)), (45.22, (3, 0)), (42.9, (4, 0)), (43.38,\n (5, 0)), (44.5, (6, 0)), (45.14, (7, 0)), (46.84, (8, 0)), (48.38, (9, \n 0))]], [[(40.64, (0, 0)), (47.1, (0, 10)), (49.92, (0, 20)), (49.44, (0,\n 30)), (50.34, (0, 40)), (50.04, (0, 50)), (51.74, (0, 60)), (52.76, (0,\n 70)), (52.68, (0, 80)), (53.58, (0, 90)), (52.98, (1, 0)), (53.26, (2, \n 0)), (56.24, (3, 0)), (56.82, (4, 0)), (58.14, (5, 0)), (58.52, (6, 0)),\n (58.98, (7, 0)), (58.94, (8, 0)), (59.86, (9, 0))], [(41.58, (0, 0)), (\n 46.48, (0, 10)), (47.92, (0, 20)), (50.06, (0, 30)), (50.14, (0, 40)),\n (51.46, (0, 50)), (51.9, (0, 60)), (51.72, (0, 70)), (52.28, (0, 80)),\n (53.14, (0, 90)), (53.72, (1, 0)), (56.16, (2, 0)), (55.8, (3, 0)), (\n 56.62, (4, 0)), (57.0, (5, 0)), (57.18, (6, 0)), (58.38, (7, 0)), (\n 57.72, (8, 0)), (59.48, (9, 0))], [(38.64, (0, 0)), (44.78, (0, 10)), (\n 48.06, (0, 20)), (49.98, (0, 30)), (51.24, (0, 40)), (51.74, (0, 50)),\n (52.98, (0, 60)), (52.9, (0, 70)), (53.32, (0, 80)), (53.58, (0, 90)),\n (53.64, (1, 0)), (55.78, (2, 0)), (56.0, (3, 0)), (56.8, (4, 0)), (\n 57.82, (5, 0)), (58.48, (6, 0)), (59.02, (7, 0)), (59.48, (8, 0)), (\n 60.04, (9, 0))]], [[(32.08, (0, 0)), (40.42, (0, 10)), (42.78, (0, 20)),\n (44.3, (0, 30)), (45.2, (0, 40)), (46.54, (0, 50)), (47.38, (0, 60)), (\n 48.72, (0, 70)), (49.76, (0, 80)), (50.26, (0, 90)), (50.82, (1, 0)), (\n 52.58, (2, 0)), (53.1, (3, 0)), (53.72, (4, 0)), (54.38, (5, 0)), (\n 55.82, (6, 0)), (56.16, (7, 0)), (56.82, (8, 0)), (56.32, (9, 0))], [(\n 32.16, (0, 0)), (38.64, (0, 10)), (41.44, (0, 20)), (43.32, (0, 30)), (\n 45.16, (0, 40)), (46.6, (0, 50)), (47.62, (0, 60)), (48.66, (0, 70)), (\n 48.04, (0, 80)), (49.1, (0, 90)), (47.78, (1, 0)), (51.42, (2, 0)), (\n 53.5, (3, 0)), (54.44, (4, 0)), (55.06, (5, 0)), (56.06, (6, 0)), (55.5,\n (7, 0)), (55.92, (8, 0)), (57.0, (9, 0))], [(34.0, (0, 0)), (38.46, (0,\n 10)), (43.88, (0, 20)), (45.98, (0, 30)), (46.84, (0, 40)), (47.86, (0,\n 50)), (48.6, (0, 60)), (48.88, (0, 70)), (49.5, (0, 80)), (49.52, (0, \n 90)), (49.88, (1, 0)), (51.24, (2, 0)), (52.22, (3, 0)), (54.4, (4, 0)),\n (54.84, (5, 0)), (55.24, (6, 0)), (56.74, (7, 0)), (57.36, (8, 0)), (\n 55.98, (9, 0))]], [[(24.04, (0, 0)), (30.7, (0, 10)), (31.46, (0, 20)),\n (31.62, (0, 30)), (32.96, (0, 40)), (33.66, (0, 50)), (36.06, (0, 60)),\n (34.78, (0, 70)), (34.44, (0, 80)), (36.38, (0, 90)), (36.14, (1, 0)),\n (42.62, (2, 0)), (42.96, (3, 0)), (44.54, (4, 0)), (45.38, (5, 0)), (\n 45.94, (6, 0)), (46.06, (7, 0)), (45.78, (8, 0)), (48.06, (9, 0))], [(\n 31.68, (0, 0)), (31.64, (0, 10)), (30.6, (0, 20)), (31.94, (0, 30)), (\n 32.92, (0, 40)), (30.6, (0, 50)), (34.02, (0, 60)), (33.92, (0, 70)), (\n 33.52, (0, 80)), (35.34, (0, 90)), (34.38, (1, 0)), (39.56, (2, 0)), (\n 39.24, (3, 0)), (39.56, (4, 0)), (42.12, (5, 0)), (41.6, (6, 0)), (\n 41.14, (7, 0)), (41.08, (8, 0)), (40.64, (9, 0))], [(26.1, (0, 0)), (\n 31.14, (0, 10)), (31.94, (0, 20)), (32.54, (0, 30)), (31.2, (0, 40)), (\n 32.7, (0, 50)), (32.48, (0, 60)), (33.32, (0, 70)), (33.16, (0, 80)), (\n 32.9, (0, 90)), (33.2, (1, 0)), (34.26, (2, 0)), (36.5, (3, 0)), (35.46,\n (4, 0)), (36.38, (5, 0)), (36.82, (6, 0)), (38.5, (7, 0)), (38.08, (8, \n 0)), (36.54, (9, 0))]], [[(30.98, (0, 0)), (28.12, (0, 10)), (30.74, (0,\n 20)), (31.84, (0, 30)), (37.32, (0, 40)), (35.24, (0, 50)), (37.64, (0,\n 60)), (39.76, (0, 70)), (38.4, (0, 80)), (37.0, (0, 90)), (34.28, (1, 0\n )), (39.84, (2, 0)), (39.24, (3, 0)), (35.54, (4, 0)), (38.84, (5, 0)),\n (38.24, (6, 0)), (39.64, (7, 0)), (39.56, (8, 0)), (39.18, (9, 0))], [(\n 28.58, (0, 0)), (27.88, (0, 10)), (26.44, (0, 20)), (29.62, (0, 30)), (\n 30.08, (0, 40)), (33.2, (0, 50)), (32.54, (0, 60)), (32.0, (0, 70)), (\n 33.42, (0, 80)), (33.24, (0, 90)), (32.06, (1, 0)), (34.72, (2, 0)), (\n 37.78, (3, 0)), (36.52, (4, 0)), (35.34, (5, 0)), (35.88, (6, 0)), (\n 35.78, (7, 0)), (33.82, (8, 0)), (33.92, (9, 0))], [(22.04, (0, 0)), (\n 27.34, (0, 10)), (26.34, (0, 20)), (23.58, (0, 30)), (22.72, (0, 40)),\n (22.04, (0, 50)), (20.76, (0, 60)), (20.8, (0, 70)), (20.7, (0, 80)), (\n 20.74, (0, 90)), (20.74, (1, 0)), (20.7, (2, 0)), (20.58, (3, 0)), (\n 21.24, (4, 0)), (20.68, (5, 0)), (20.72, (6, 0)), (20.72, (7, 0)), (\n 20.76, (8, 0)), (20.7, (9, 0))]]]'], {}), '([[[(26.62, (0, 0)), (36.98, (0, 10)), (37.24, (0, 20)), (33.96, (0,\n 30)), (38.6, (0, 40)), (37.58, (0, 50)), (34.84, (0, 60)), (33.14, (0, \n 70)), (36.48, (0, 80)), (39.88, (0, 90)), (46.42, (1, 0)), (48.9, (2, 0\n )), (50.02, (3, 0)), (51.38, (4, 0)), (51.82, (5, 0)), (51.04, (6, 0)),\n (51.32, (7, 0)), (50.78, (8, 0)), (53.98, (9, 0))], [(31.02, (0, 0)), (\n 37.02, (0, 10)), (38.12, (0, 20)), (39.04, (0, 30)), (41.32, (0, 40)),\n (43.06, (0, 50)), (42.68, (0, 60)), (43.52, (0, 70)), (43.16, (0, 80)),\n (44.16, (0, 90)), (45.48, (1, 0)), (48.8, (2, 0)), (49.62, (3, 0)), (\n 51.94, (4, 0)), (52.74, (5, 0)), (52.34, (6, 0)), (53.98, (7, 0)), (\n 54.4, (8, 0)), (55.66, (9, 0))], [(31.4, (0, 0)), (38.42, (0, 10)), (\n 38.96, (0, 20)), (40.42, (0, 30)), (42.34, (0, 40)), (42.54, (0, 50)),\n (43.52, (0, 60)), (44.2, (0, 70)), (46.4, (0, 80)), (45.92, (0, 90)), (\n 46.84, (1, 0)), (48.7, (2, 0)), (49.34, (3, 0)), (51.22, (4, 0)), (52.5,\n (5, 0)), (53.86, (6, 0)), (54.6, (7, 0)), (53.94, (8, 0)), (55.1, (9, 0\n ))]], [[(31.16, (0, 0)), (35.84, (0, 10)), (34.28, (0, 20)), (32.74, (0,\n 30)), (35.14, (0, 40)), (36.24, (0, 50)), (36.76, (0, 60)), (36.62, (0,\n 70)), (22.6, (0, 80)), (30.56, (0, 90)), (38.22, (1, 0)), (44.24, (2, 0\n )), (46.46, (3, 0)), (46.7, (4, 0)), (48.12, (5, 0)), (49.18, (6, 0)),\n (47.68, (7, 0)), (51.2, (8, 0)), (48.18, (9, 0))], [(30.4, (0, 0)), (\n 32.96, (0, 10)), (35.56, (0, 20)), (39.16, (0, 30)), (39.52, (0, 40)),\n (40.1, (0, 50)), (39.78, (0, 60)), (39.94, (0, 70)), (40.78, (0, 80)),\n (41.08, (0, 90)), (42.02, (1, 0)), (44.78, (2, 0)), (45.62, (3, 0)), (\n 46.82, (4, 0)), (46.76, (5, 0)), (49.34, (6, 0)), (49.72, (7, 0)), (\n 49.9, (8, 0)), (51.46, (9, 0))], [(29.14, (0, 0)), (31.28, (0, 10)), (\n 33.06, (0, 20)), (32.94, (0, 30)), (34.04, (0, 40)), (33.58, (0, 50)),\n (34.3, (0, 60)), (35.04, (0, 70)), (35.7, (0, 80)), (37.46, (0, 90)), (\n 37.36, (1, 0)), (41.9, (2, 0)), (45.22, (3, 0)), (42.9, (4, 0)), (43.38,\n (5, 0)), (44.5, (6, 0)), (45.14, (7, 0)), (46.84, (8, 0)), (48.38, (9, \n 0))]], [[(40.64, (0, 0)), (47.1, (0, 10)), (49.92, (0, 20)), (49.44, (0,\n 30)), (50.34, (0, 40)), (50.04, (0, 50)), (51.74, (0, 60)), (52.76, (0,\n 70)), (52.68, (0, 80)), (53.58, (0, 90)), (52.98, (1, 0)), (53.26, (2, \n 0)), (56.24, (3, 0)), (56.82, (4, 0)), (58.14, (5, 0)), (58.52, (6, 0)),\n (58.98, (7, 0)), (58.94, (8, 0)), (59.86, (9, 0))], [(41.58, (0, 0)), (\n 46.48, (0, 10)), (47.92, (0, 20)), (50.06, (0, 30)), (50.14, (0, 40)),\n (51.46, (0, 50)), (51.9, (0, 60)), (51.72, (0, 70)), (52.28, (0, 80)),\n (53.14, (0, 90)), (53.72, (1, 0)), (56.16, (2, 0)), (55.8, (3, 0)), (\n 56.62, (4, 0)), (57.0, (5, 0)), (57.18, (6, 0)), (58.38, (7, 0)), (\n 57.72, (8, 0)), (59.48, (9, 0))], [(38.64, (0, 0)), (44.78, (0, 10)), (\n 48.06, (0, 20)), (49.98, (0, 30)), (51.24, (0, 40)), (51.74, (0, 50)),\n (52.98, (0, 60)), (52.9, (0, 70)), (53.32, (0, 80)), (53.58, (0, 90)),\n (53.64, (1, 0)), (55.78, (2, 0)), (56.0, (3, 0)), (56.8, (4, 0)), (\n 57.82, (5, 0)), (58.48, (6, 0)), (59.02, (7, 0)), (59.48, (8, 0)), (\n 60.04, (9, 0))]], [[(32.08, (0, 0)), (40.42, (0, 10)), (42.78, (0, 20)),\n (44.3, (0, 30)), (45.2, (0, 40)), (46.54, (0, 50)), (47.38, (0, 60)), (\n 48.72, (0, 70)), (49.76, (0, 80)), (50.26, (0, 90)), (50.82, (1, 0)), (\n 52.58, (2, 0)), (53.1, (3, 0)), (53.72, (4, 0)), (54.38, (5, 0)), (\n 55.82, (6, 0)), (56.16, (7, 0)), (56.82, (8, 0)), (56.32, (9, 0))], [(\n 32.16, (0, 0)), (38.64, (0, 10)), (41.44, (0, 20)), (43.32, (0, 30)), (\n 45.16, (0, 40)), (46.6, (0, 50)), (47.62, (0, 60)), (48.66, (0, 70)), (\n 48.04, (0, 80)), (49.1, (0, 90)), (47.78, (1, 0)), (51.42, (2, 0)), (\n 53.5, (3, 0)), (54.44, (4, 0)), (55.06, (5, 0)), (56.06, (6, 0)), (55.5,\n (7, 0)), (55.92, (8, 0)), (57.0, (9, 0))], [(34.0, (0, 0)), (38.46, (0,\n 10)), (43.88, (0, 20)), (45.98, (0, 30)), (46.84, (0, 40)), (47.86, (0,\n 50)), (48.6, (0, 60)), (48.88, (0, 70)), (49.5, (0, 80)), (49.52, (0, \n 90)), (49.88, (1, 0)), (51.24, (2, 0)), (52.22, (3, 0)), (54.4, (4, 0)),\n (54.84, (5, 0)), (55.24, (6, 0)), (56.74, (7, 0)), (57.36, (8, 0)), (\n 55.98, (9, 0))]], [[(24.04, (0, 0)), (30.7, (0, 10)), (31.46, (0, 20)),\n (31.62, (0, 30)), (32.96, (0, 40)), (33.66, (0, 50)), (36.06, (0, 60)),\n (34.78, (0, 70)), (34.44, (0, 80)), (36.38, (0, 90)), (36.14, (1, 0)),\n (42.62, (2, 0)), (42.96, (3, 0)), (44.54, (4, 0)), (45.38, (5, 0)), (\n 45.94, (6, 0)), (46.06, (7, 0)), (45.78, (8, 0)), (48.06, (9, 0))], [(\n 31.68, (0, 0)), (31.64, (0, 10)), (30.6, (0, 20)), (31.94, (0, 30)), (\n 32.92, (0, 40)), (30.6, (0, 50)), (34.02, (0, 60)), (33.92, (0, 70)), (\n 33.52, (0, 80)), (35.34, (0, 90)), (34.38, (1, 0)), (39.56, (2, 0)), (\n 39.24, (3, 0)), (39.56, (4, 0)), (42.12, (5, 0)), (41.6, (6, 0)), (\n 41.14, (7, 0)), (41.08, (8, 0)), (40.64, (9, 0))], [(26.1, (0, 0)), (\n 31.14, (0, 10)), (31.94, (0, 20)), (32.54, (0, 30)), (31.2, (0, 40)), (\n 32.7, (0, 50)), (32.48, (0, 60)), (33.32, (0, 70)), (33.16, (0, 80)), (\n 32.9, (0, 90)), (33.2, (1, 0)), (34.26, (2, 0)), (36.5, (3, 0)), (35.46,\n (4, 0)), (36.38, (5, 0)), (36.82, (6, 0)), (38.5, (7, 0)), (38.08, (8, \n 0)), (36.54, (9, 0))]], [[(30.98, (0, 0)), (28.12, (0, 10)), (30.74, (0,\n 20)), (31.84, (0, 30)), (37.32, (0, 40)), (35.24, (0, 50)), (37.64, (0,\n 60)), (39.76, (0, 70)), (38.4, (0, 80)), (37.0, (0, 90)), (34.28, (1, 0\n )), (39.84, (2, 0)), (39.24, (3, 0)), (35.54, (4, 0)), (38.84, (5, 0)),\n (38.24, (6, 0)), (39.64, (7, 0)), (39.56, (8, 0)), (39.18, (9, 0))], [(\n 28.58, (0, 0)), (27.88, (0, 10)), (26.44, (0, 20)), (29.62, (0, 30)), (\n 30.08, (0, 40)), (33.2, (0, 50)), (32.54, (0, 60)), (32.0, (0, 70)), (\n 33.42, (0, 80)), (33.24, (0, 90)), (32.06, (1, 0)), (34.72, (2, 0)), (\n 37.78, (3, 0)), (36.52, (4, 0)), (35.34, (5, 0)), (35.88, (6, 0)), (\n 35.78, (7, 0)), (33.82, (8, 0)), (33.92, (9, 0))], [(22.04, (0, 0)), (\n 27.34, (0, 10)), (26.34, (0, 20)), (23.58, (0, 30)), (22.72, (0, 40)),\n (22.04, (0, 50)), (20.76, (0, 60)), (20.8, (0, 70)), (20.7, (0, 80)), (\n 20.74, (0, 90)), (20.74, (1, 0)), (20.7, (2, 0)), (20.58, (3, 0)), (\n 21.24, (4, 0)), (20.68, (5, 0)), (20.72, (6, 0)), (20.72, (7, 0)), (\n 20.76, (8, 0)), (20.7, (9, 0))]]])\n', (8001, 14354), True, 'import numpy as np\n'), ((15593, 15625), 'numpy.array', 'np.array', (['[16, 8, 512, 32, 4, 2]'], {}), '([16, 8, 512, 32, 4, 2])\n', (15601, 15625), True, 'import numpy as np\n'), ((15861, 16466), 'numpy.array', 'np.array', (['[[(33.22, 9), (37.56, 19), (27.46, 49), (31.48, 99), (35.3, 199), (36.76, \n 299)], [(53.32, 9), (54.36, 19), (59.36, 49), (65.92, 99), (70.5, 199),\n (72.34, 299)], [(45.0, 9), (46.76, 19), (51.0, 49), (37.92, 99), (41.7,\n 199), (43.46, 299)], [(59.06, 9), (61.1, 19), (64.22, 49), (67.64, 99),\n (70.18, 199), (71.64, 299)], [(52.56, 9), (55.16, 19), (60.88, 49), (\n 62.08, 99), (63.56, 199), (64.02, 299)], [(56.84, 9), (57.9, 19), (\n 60.82, 49), (66.88, 99), (68.14, 199), (70.58, 299)], [(61.1, 9), (\n 62.88, 19), (62.2, 49), (64.22, 99), (68.14, 199), (70.04, 299)]]'], {}), '([[(33.22, 9), (37.56, 19), (27.46, 49), (31.48, 99), (35.3, 199),\n (36.76, 299)], [(53.32, 9), (54.36, 19), (59.36, 49), (65.92, 99), (\n 70.5, 199), (72.34, 299)], [(45.0, 9), (46.76, 19), (51.0, 49), (37.92,\n 99), (41.7, 199), (43.46, 299)], [(59.06, 9), (61.1, 19), (64.22, 49),\n (67.64, 99), (70.18, 199), (71.64, 299)], [(52.56, 9), (55.16, 19), (\n 60.88, 49), (62.08, 99), (63.56, 199), (64.02, 299)], [(56.84, 9), (\n 57.9, 19), (60.82, 49), (66.88, 99), (68.14, 199), (70.58, 299)], [(\n 61.1, 9), (62.88, 19), (62.2, 49), (64.22, 99), (68.14, 199), (70.04, \n 299)]])\n', (15869, 16466), True, 'import numpy as np\n'), ((16501, 16537), 'numpy.array', 'np.array', (['[2, 12, 4, 32, 8, 16, 512]'], {}), '([2, 12, 4, 32, 8, 16, 512])\n', (16509, 16537), True, 'import numpy as np\n'), ((16685, 17294), 'numpy.array', 'np.array', (['[[(38.64, 9), (39.04, 19), (40.1, 49), (42.48, 99), (42.66, 199), (39.58, \n 299)], [(60.68, 9), (63.34, 19), (67.46, 49), (69.96, 99), (74.28, 199),\n (75.72, 299)], [(58.88, 9), (61.44, 19), (64.58, 49), (68.78, 99), (\n 70.36, 199), (72.16, 299)], [(58.34, 9), (59.24, 19), (61.6, 49), (\n 64.72, 99), (70.88, 199), (71.5, 299)], [(51.14, 9), (51.92, 19), (\n 51.32, 49), (52.94, 99), (53.18, 199), (54.18, 299)], [(52.74, 9), (\n 57.86, 19), (60.3, 49), (66.56, 99), (69.74, 199), (70.34, 299)], [(\n 64.76, 9), (68.42, 19), (72.32, 49), (75.66, 99), (78.48, 199), (80.12,\n 299)]]'], {}), '([[(38.64, 9), (39.04, 19), (40.1, 49), (42.48, 99), (42.66, 199),\n (39.58, 299)], [(60.68, 9), (63.34, 19), (67.46, 49), (69.96, 99), (\n 74.28, 199), (75.72, 299)], [(58.88, 9), (61.44, 19), (64.58, 49), (\n 68.78, 99), (70.36, 199), (72.16, 299)], [(58.34, 9), (59.24, 19), (\n 61.6, 49), (64.72, 99), (70.88, 199), (71.5, 299)], [(51.14, 9), (51.92,\n 19), (51.32, 49), (52.94, 99), (53.18, 199), (54.18, 299)], [(52.74, 9),\n (57.86, 19), (60.3, 49), (66.56, 99), (69.74, 199), (70.34, 299)], [(\n 64.76, 9), (68.42, 19), (72.32, 49), (75.66, 99), (78.48, 199), (80.12,\n 299)]])\n', (16693, 17294), True, 'import numpy as np\n'), ((17335, 17371), 'numpy.array', 'np.array', (['[2, 32, 16, 12, 4, 8, 512]'], {}), '([2, 32, 16, 12, 4, 8, 512])\n', (17343, 17371), True, 'import numpy as np\n')] |
#!/usr/bin/python
from tkinter import *
from tkinter import filedialog
from PIL import Image, ImageTk
import cv2
import glob
import numpy as np
import tensorflow as tf
from train import build_forward
from utils import train_utils
from utils.annolist import AnnotationLib as al
from utils.stitch_wrapper import stitch_rects
from utils.train_utils import add_rectangles
from utils.rect import Rect
from utils.stitch_wrapper import stitch_rects
from evaluate import add_rectangles
# Variabel Konstan
JENIS_SEL_DARAH_PUTIH = 5
def resizeImage(f):
return cv2.resize(f, (640, 480))
def segmentasiCitra(citraKecil, sess):
# new_img, rects = add_rectangles(H, [img], np_pred_confidences, np_pred_boxes,
# use_stitching=True, rnn_len=H['rnn_len'], min_conf=0.7,
# show_suppressed=False)
# Olah menggunakan TensorBox
return spasial, cWBC
def klasifikasiWBC(citra, dataSpasialWBC):
return data
def prosesCitra(citra):
citraKecil = cv2.resize(citra, (640, 480))
dataSpasialWBC, citraWBC = segmentasiCitra(citraKecil)
data = klasifikasiWBC(citra, dataSpasialWBC)
return data, citraKecil
def prosesCitraBanyak(alamatFolder):
listCitra = glob.glob(alamatFolder + "*.png")
segmenSaver = tf.train.Saver()
with tf.Session() as segmenSess:
segmenSess.run(tf.initialize_all_variables())
segmenSaver.restore(segmenSess, 'segmensave.ckpt') # TODO edit ini sesuai nama file
for indexCitra in range(0, listCitra.size):
citra = cv2.imread(listCitra[indexCitra])
citraKecil = cv2.resize(citra, (640, 480))
dataSpasialWBC, citraWBC = segmentasiCitra(citraKecil, segmenSess)
data = klasifikasiWBC(citra, dataSpasialWBC)
return data, citraKecil
class GUI(Frame):
def __init__(self, parent):
Frame.__init__(self, parent)
self.dataJumlahWBC = np.empty(JENIS_SEL_DARAH_PUTIH)
self.parent = parent
self.initUI()
def initUI(self):
self.parent.title("Cidar")
menubar = Menu(self.parent)
self.parent.config(menu=menubar)
fileMenu = Menu(menubar)
fileMenu.add_command(label="Buka Satuan", underline=0, command=self.tangkapCitraSatuan())
fileMenu.add_command(label="Buka Banyak", underline=0, command=self.tangkapCitraBanyak())
fileMenu.add_command(label="Simpan Data", underline=0, command=self.simpanData())
fileMenu.add_separator()
fileMenu.add_command(label="Keluar", underline=0, command=self.onExit)
menubar.add_cascade(label="Berkas", underline=0, menu=fileMenu)
self.pack()
def tangkapCitraSatuan(self):
ftypes = [('Portable Network Graphics', '*.png'), ('JPEG', '*.jpg')]
dlg = filedialog.Open(self, filetypes=ftypes)
fl = dlg.show()
if fl != '':
self.img = Image.open(fl)
f = ImageTk.PhotoImage(self.img)
jumlahWBC, hasilResize = prosesCitra(f)
self.dataJumlahWBC = self.dataJumlahWBC + jumlahWBC # Penambahan untuk update data
label = Label(self, height="480", width="640", image=hasilResize) # img nanti di resize dulu dari hasil TensorBox
label.image = hasilResize
label.pack(side="left", expand="no")
def tangkapCitraBanyak(self):
dlg = filedialog.askdirectory()
dirC = dlg.show()
if dirC != '':
self.dataJumlahWBC, citraKotakan = prosesCitraBanyak(dirC)
def simpanData(self):
pass
def onExit(self):
self.quit()
def main():
# Inisialisasi TensorBox dan TensorFlow
global seGmentasi
global seKlasifikasi
root = Tk()
root.geometry("1024x768+0+0")
app = GUI(root)
root.mainloop()
if __name__ == '__main__':
main()
# import os
# import cv2
# import math
# import numpy as np
# from tkinter import *
# from random import randint
#
# # logo = PhotoImage(file='contohbagus.gif')
#
# # GUI Cidar
# top = Tk()
# # top.iconbitmap(lokasi + '\logo.ico') #Set logo
# frame = Frame(top)
# frame.pack()
#
# C = Canvas(top, bg="white", height=600, width=800)
#
#
# def tangkapCitraSatuan():
# pass
#
#
# def tangkapCitraBanyak():
# pass
#
#
# BtnMulaiSatuan = Button(top, text='Ambil Citra', command=lambda: tangkapCitraSatuan())
# BtnMulaiBanyak = Button(top, text='Ambil Banyak', command=lambda: tangkapCitraBanyak())
# BtnKeluar = Button(top, text='Keluar', command=lambda: top.quit())
#
# C.pack(side=TOP)
# BtnMulaiSatuan.pack(padx=5, side=LEFT)
# BtnMulaiBanyak.pack(padx=5, side=LEFT)
# BtnKeluar.pack(padx=5, side=LEFT)
#
# # Fungsi mulai di sini
#
# top.title('Cidar')
# # top.tk.call('wm', 'iconphoto', top._w, logo)
# top.mainloop()
| [
"PIL.ImageTk.PhotoImage",
"tensorflow.train.Saver",
"tkinter.filedialog.Open",
"numpy.empty",
"tensorflow.Session",
"PIL.Image.open",
"tkinter.filedialog.askdirectory",
"cv2.imread",
"tensorflow.initialize_all_variables",
"glob.glob",
"cv2.resize"
] | [((581, 606), 'cv2.resize', 'cv2.resize', (['f', '(640, 480)'], {}), '(f, (640, 480))\n', (591, 606), False, 'import cv2\n'), ((1067, 1096), 'cv2.resize', 'cv2.resize', (['citra', '(640, 480)'], {}), '(citra, (640, 480))\n', (1077, 1096), False, 'import cv2\n'), ((1295, 1328), 'glob.glob', 'glob.glob', (["(alamatFolder + '*.png')"], {}), "(alamatFolder + '*.png')\n", (1304, 1328), False, 'import glob\n'), ((1348, 1364), 'tensorflow.train.Saver', 'tf.train.Saver', ([], {}), '()\n', (1362, 1364), True, 'import tensorflow as tf\n'), ((1375, 1387), 'tensorflow.Session', 'tf.Session', ([], {}), '()\n', (1385, 1387), True, 'import tensorflow as tf\n'), ((2010, 2041), 'numpy.empty', 'np.empty', (['JENIS_SEL_DARAH_PUTIH'], {}), '(JENIS_SEL_DARAH_PUTIH)\n', (2018, 2041), True, 'import numpy as np\n'), ((2910, 2949), 'tkinter.filedialog.Open', 'filedialog.Open', (['self'], {'filetypes': 'ftypes'}), '(self, filetypes=ftypes)\n', (2925, 2949), False, 'from tkinter import filedialog\n'), ((3507, 3532), 'tkinter.filedialog.askdirectory', 'filedialog.askdirectory', ([], {}), '()\n', (3530, 3532), False, 'from tkinter import filedialog\n'), ((1427, 1456), 'tensorflow.initialize_all_variables', 'tf.initialize_all_variables', ([], {}), '()\n', (1454, 1456), True, 'import tensorflow as tf\n'), ((1625, 1658), 'cv2.imread', 'cv2.imread', (['listCitra[indexCitra]'], {}), '(listCitra[indexCitra])\n', (1635, 1658), False, 'import cv2\n'), ((1685, 1714), 'cv2.resize', 'cv2.resize', (['citra', '(640, 480)'], {}), '(citra, (640, 480))\n', (1695, 1714), False, 'import cv2\n'), ((3023, 3037), 'PIL.Image.open', 'Image.open', (['fl'], {}), '(fl)\n', (3033, 3037), False, 'from PIL import Image, ImageTk\n'), ((3055, 3083), 'PIL.ImageTk.PhotoImage', 'ImageTk.PhotoImage', (['self.img'], {}), '(self.img)\n', (3073, 3083), False, 'from PIL import Image, ImageTk\n')] |
from __future__ import print_function, division
import torch.utils.data as data
from torch.utils.data import Dataset, DataLoader
import torch
import numpy as np
import os
import os.path
import cv2
import scipy.io as scio
def transformation_from_points(points1, scale):
points = [[70, 112],
[110, 112],
[90, 150]]
points2 = np.array(points) * scale
points2 = points2.astype(np.float64)
points1 = points1.astype(np.float64)
c1 = np.mean(points1, axis=0)
c2 = np.mean(points2, axis=0)
points1 -= c1
points2 -= c2
s1 = np.std(points1)
s2 = np.std(points2)
points1 /= s1
points2 /= s2
U, S, Vt = np.linalg.svd(np.matmul(points1.T, points2))
R = (np.matmul(U, Vt)).T
sR = (s2 / s1) * R
T = c2.reshape(2,1) - (s2 / s1) * np.matmul(R, c1.reshape(2,1))
M = np.concatenate((sR, T), axis=1)
return M
class ImageLoader(object):
def __init__(self, mode='test'):
self.scale = 2
self.crop_height = 134 * self.scale
self.crop_width = 134 * self.scale
self.crop_center_y_offset = 10 * self.scale
self.output_scale = (260, 260)
self.ori_scale = (178 * self.scale, 218 * self.scale)
self.random_x = 0
self.random_y = 0
self.flip = 0
if mode == 'train':
self.flip = np.random.randint(0, 2)
self.random_x = np.random.randint(-3, 4)
self.random_y = np.random.randint(-3, 4)
def image_loader(self, path, points):
if os.path.exists(path):
img = cv2.imread(path)
three_points = np.zeros((3, 2))
three_points[0] = np.array(points[:2]) # the location of the left eye
three_points[1] = np.array(points[2:4]) # the location of the right eye
three_points[2] = np.array([(points[6] + points[8]) / 2, (points[7] + points[9]) / 2]) # the location of the center of the mouth
three_points.astype(np.float32)
M = transformation_from_points(three_points, self.scale)
align_img = cv2.warpAffine(img, M, self.ori_scale, borderValue=[127, 127, 127])
l = int(round(self.ori_scale[0] / 2 - self.crop_width / 2 + self.random_x))
r = int(round(self.ori_scale[0] / 2 + self.crop_width / 2 + self.random_x))
t = int(round(self.ori_scale[1] / 2 - self.crop_height / 2 + self.crop_center_y_offset + self.random_y))
d = int(round(self.ori_scale[1] / 2 + self.crop_height / 2 + self.crop_center_y_offset + self.random_y))
align_img2 = align_img[t:d, l:r, :]
align_img2 = cv2.resize(align_img2, self.output_scale)
return align_img2
else:
raise ("image = 0")
| [
"cv2.resize",
"numpy.std",
"os.path.exists",
"numpy.zeros",
"cv2.imread",
"cv2.warpAffine",
"numpy.mean",
"numpy.array",
"numpy.random.randint",
"numpy.matmul",
"numpy.concatenate"
] | [((480, 504), 'numpy.mean', 'np.mean', (['points1'], {'axis': '(0)'}), '(points1, axis=0)\n', (487, 504), True, 'import numpy as np\n'), ((514, 538), 'numpy.mean', 'np.mean', (['points2'], {'axis': '(0)'}), '(points2, axis=0)\n', (521, 538), True, 'import numpy as np\n'), ((585, 600), 'numpy.std', 'np.std', (['points1'], {}), '(points1)\n', (591, 600), True, 'import numpy as np\n'), ((610, 625), 'numpy.std', 'np.std', (['points2'], {}), '(points2)\n', (616, 625), True, 'import numpy as np\n'), ((851, 882), 'numpy.concatenate', 'np.concatenate', (['(sR, T)'], {'axis': '(1)'}), '((sR, T), axis=1)\n', (865, 882), True, 'import numpy as np\n'), ((363, 379), 'numpy.array', 'np.array', (['points'], {}), '(points)\n', (371, 379), True, 'import numpy as np\n'), ((692, 721), 'numpy.matmul', 'np.matmul', (['points1.T', 'points2'], {}), '(points1.T, points2)\n', (701, 721), True, 'import numpy as np\n'), ((732, 748), 'numpy.matmul', 'np.matmul', (['U', 'Vt'], {}), '(U, Vt)\n', (741, 748), True, 'import numpy as np\n'), ((1535, 1555), 'os.path.exists', 'os.path.exists', (['path'], {}), '(path)\n', (1549, 1555), False, 'import os\n'), ((1351, 1374), 'numpy.random.randint', 'np.random.randint', (['(0)', '(2)'], {}), '(0, 2)\n', (1368, 1374), True, 'import numpy as np\n'), ((1403, 1427), 'numpy.random.randint', 'np.random.randint', (['(-3)', '(4)'], {}), '(-3, 4)\n', (1420, 1427), True, 'import numpy as np\n'), ((1456, 1480), 'numpy.random.randint', 'np.random.randint', (['(-3)', '(4)'], {}), '(-3, 4)\n', (1473, 1480), True, 'import numpy as np\n'), ((1575, 1591), 'cv2.imread', 'cv2.imread', (['path'], {}), '(path)\n', (1585, 1591), False, 'import cv2\n'), ((1619, 1635), 'numpy.zeros', 'np.zeros', (['(3, 2)'], {}), '((3, 2))\n', (1627, 1635), True, 'import numpy as np\n'), ((1666, 1686), 'numpy.array', 'np.array', (['points[:2]'], {}), '(points[:2])\n', (1674, 1686), True, 'import numpy as np\n'), ((1749, 1770), 'numpy.array', 'np.array', (['points[2:4]'], {}), '(points[2:4])\n', (1757, 1770), True, 'import numpy as np\n'), ((1833, 1901), 'numpy.array', 'np.array', (['[(points[6] + points[8]) / 2, (points[7] + points[9]) / 2]'], {}), '([(points[6] + points[8]) / 2, (points[7] + points[9]) / 2])\n', (1841, 1901), True, 'import numpy as np\n'), ((2081, 2148), 'cv2.warpAffine', 'cv2.warpAffine', (['img', 'M', 'self.ori_scale'], {'borderValue': '[127, 127, 127]'}), '(img, M, self.ori_scale, borderValue=[127, 127, 127])\n', (2095, 2148), False, 'import cv2\n'), ((2632, 2673), 'cv2.resize', 'cv2.resize', (['align_img2', 'self.output_scale'], {}), '(align_img2, self.output_scale)\n', (2642, 2673), False, 'import cv2\n')] |
# encoding: utf-8
# Copyright 2022 Huawei Technologies Co., Ltd
#
# 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.
# ============================================================================
""" Base dataset loader """
import numpy as np
class BaseDataset:
"""
Base class of reid dataset
"""
def get_imagedata_info(self, data):
""" Get number of persons, images and cams from image data """
pids, cams = [], []
for _, pid, camid in data:
pids += [pid]
cams += [camid]
pids = set(pids)
cams = set(cams)
num_pids = len(pids)
num_cams = len(cams)
num_imgs = len(data)
return num_pids, num_imgs, num_cams
def get_videodata_info(self, data, return_tracklet_stats=False):
""" Get number of persons, images and cams [and tracklet_stats if flag] from video data """
pids, cams, tracklet_stats = [], [], []
for img_paths, pid, camid in data:
pids += [pid]
cams += [camid]
tracklet_stats += [len(img_paths)]
pids = set(pids)
cams = set(cams)
num_pids = len(pids)
num_cams = len(cams)
num_tracklets = len(data)
if return_tracklet_stats:
return num_pids, num_tracklets, num_cams, tracklet_stats
return num_pids, num_tracklets, num_cams
def print_dataset_statistics(self, **kwargs):
""" print dataset statistic in """
raise NotImplementedError
class BaseImageDataset(BaseDataset):
"""
Base class of image reid dataset
"""
def print_dataset_statistics(self, train, query, gallery):
""" Print train, query and gallery subset statistics in console """
num_train_pids, num_train_imgs, num_train_cams = self.get_imagedata_info(train)
num_query_pids, num_query_imgs, num_query_cams = self.get_imagedata_info(query)
num_gallery_pids, num_gallery_imgs, num_gallery_cams = self.get_imagedata_info(gallery)
print("Dataset statistics:")
print(" ----------------------------------------")
print(" subset | # ids | # images | # cameras")
print(" ----------------------------------------")
print(" train | {:5d} | {:8d} | {:9d}".format(num_train_pids, num_train_imgs, num_train_cams))
print(" query | {:5d} | {:8d} | {:9d}".format(num_query_pids, num_query_imgs, num_query_cams))
print(" gallery | {:5d} | {:8d} | {:9d}".format(num_gallery_pids, num_gallery_imgs, num_gallery_cams))
print(" ----------------------------------------")
class BaseVideoDataset(BaseDataset):
"""
Base class of video reid dataset
"""
def print_dataset_statistics(self, train, query, gallery):
""" Print train, query and gallery subset statistics in console """
num_train_pids, num_train_tracklets, num_train_cams, train_tracklet_stats = \
self.get_videodata_info(train, return_tracklet_stats=True)
num_query_pids, num_query_tracklets, num_query_cams, query_tracklet_stats = \
self.get_videodata_info(query, return_tracklet_stats=True)
num_gallery_pids, num_gallery_tracklets, num_gallery_cams, gallery_tracklet_stats = \
self.get_videodata_info(gallery, return_tracklet_stats=True)
tracklet_stats = train_tracklet_stats + query_tracklet_stats + gallery_tracklet_stats
min_num = np.min(tracklet_stats)
max_num = np.max(tracklet_stats)
avg_num = np.mean(tracklet_stats)
print("Dataset statistics:")
print(" -------------------------------------------")
print(" subset | # ids | # tracklets | # cameras")
print(" -------------------------------------------")
print(" train | {:5d} | {:11d} | {:9d}".format(num_train_pids, num_train_tracklets, num_train_cams))
print(" query | {:5d} | {:11d} | {:9d}".format(num_query_pids, num_query_tracklets, num_query_cams))
print(" gallery | {:5d} | {:11d} | {:9d}".format(num_gallery_pids, num_gallery_tracklets, num_gallery_cams))
print(" -------------------------------------------")
print(" number of images per tracklet: {} ~ {}, average {:.2f}".format(min_num, max_num, avg_num))
print(" -------------------------------------------")
| [
"numpy.min",
"numpy.mean",
"numpy.max"
] | [((3931, 3953), 'numpy.min', 'np.min', (['tracklet_stats'], {}), '(tracklet_stats)\n', (3937, 3953), True, 'import numpy as np\n'), ((3972, 3994), 'numpy.max', 'np.max', (['tracklet_stats'], {}), '(tracklet_stats)\n', (3978, 3994), True, 'import numpy as np\n'), ((4013, 4036), 'numpy.mean', 'np.mean', (['tracklet_stats'], {}), '(tracklet_stats)\n', (4020, 4036), True, 'import numpy as np\n')] |
import numpy as np
import torch
def pad(tensor, shape, value=0):
if tensor.shape == shape: return tensor
if isinstance(tensor, np.ndarray):
padded = np.zeros(shape, dtype=tensor.dtype)
else:
padded = torch.zeros(shape)
if value != 0:
padded[:] = value
padded[tuple(map(slice, tensor.shape))] = tensor
return padded
def pad_to_largest(tensors, value=0):
shape = tuple(max(dim) for dim in zip(*(t.shape for t in tensors)))
return [pad(t, shape, value) for t in tensors] | [
"torch.zeros",
"numpy.zeros"
] | [((160, 195), 'numpy.zeros', 'np.zeros', (['shape'], {'dtype': 'tensor.dtype'}), '(shape, dtype=tensor.dtype)\n', (168, 195), True, 'import numpy as np\n'), ((217, 235), 'torch.zeros', 'torch.zeros', (['shape'], {}), '(shape)\n', (228, 235), False, 'import torch\n')] |
""" philoseismos: engineering seismologist's toolbox.
author: <NAME>
e-mail: <EMAIL> """
import struct
import numpy as np
import pandas as pd
from philoseismos.segy import gfunc
from philoseismos.segy import constants as const
class Geometry:
""" This object represents trace headers of a SEG-Y file. """
def __init__(self):
self._df = None
@classmethod
def load(cls, file: str):
""" Load the Geometry from a SEG-Y file. """
g = cls()
with open(file, 'br') as sgy:
# grab endian, number of traces, sample size, and trace length
endian = gfunc.grab_endiannes(sgy)
nt = gfunc.grab_number_of_traces(sgy)
ss = gfunc.grab_sample_format(sgy)[0]
tl = gfunc.grab_trace_length(sgy)
# skip TFH and BFH
sgy.seek(3600)
# create a matrix to store trace headers' values
data = np.empty(shape=(nt, 90), dtype=np.int32)
for i in range(nt):
# read in, unpack and store the header
raw_header = sgy.read(240)
header = struct.unpack(endian + const.THFS, raw_header[:232])
data[i] = header
# skip to the next header - one trace worth of bytes
sgy.seek(sgy.tell() + ss * tl)
# transform the matrix into a DataFrame
g._df = pd.DataFrame(data, index=range(nt), columns=const.THCOLS)
# apply scalars to elevations and coordinates
g._apply_scalars_after_unpacking()
return g
@property
def loc(self):
return self._df.loc
def _apply_scalars_after_unpacking(self):
""" Apply elevation and coordinate scalars after unpacking. """
# zero should be treated as one
self._df.replace({'ELEVSC', 0}, 1, inplace=True)
self._df.replace({'COORDSC', 0}, 1, inplace=True)
# take the absolute value of the scalars
abs_elevsc = abs(self._df.ELEVSC)
abs_coordsc = abs(self._df.COORDSC)
# if negative, to be used as a divisor
neg_elevsc_ind = self._df.ELEVSC < 0
neg_coordsc_ind = self._df.COORDSC < 0
self._df.loc[neg_elevsc_ind, 'REC_ELEV'] /= abs_elevsc
self._df.loc[neg_elevsc_ind, 'SOU_ELEV'] /= abs_elevsc
self._df.loc[neg_elevsc_ind, 'DEPTH'] /= abs_elevsc
self._df.loc[neg_elevsc_ind, 'REC_DATUM'] /= abs_elevsc
self._df.loc[neg_elevsc_ind, 'SOU_DATUM'] /= abs_elevsc
self._df.loc[neg_elevsc_ind, 'SOU_H2OD'] /= abs_elevsc
self._df.loc[neg_elevsc_ind, 'REC_H2OD'] /= abs_elevsc
self._df.loc[neg_coordsc_ind, 'SOU_X'] /= abs_coordsc
self._df.loc[neg_coordsc_ind, 'SOU_Y'] /= abs_coordsc
self._df.loc[neg_coordsc_ind, 'REC_X'] /= abs_coordsc
self._df.loc[neg_coordsc_ind, 'REC_Y'] /= abs_coordsc
self._df.loc[neg_coordsc_ind, 'CDP_X'] /= abs_coordsc
self._df.loc[neg_coordsc_ind, 'CDP_Y'] /= abs_coordsc
# if positive, to be used as a multiplier
pos_elevsc_ind = self._df.ELEVSC > 0
pos_coordsc_ind = self._df.COORDSC > 0
self._df.loc[pos_elevsc_ind, 'REC_ELEV'] *= abs_elevsc
self._df.loc[pos_elevsc_ind, 'SOU_ELEV'] *= abs_elevsc
self._df.loc[pos_elevsc_ind, 'DEPTH'] *= abs_elevsc
self._df.loc[pos_elevsc_ind, 'REC_DATUM'] *= abs_elevsc
self._df.loc[pos_elevsc_ind, 'SOU_DATUM'] *= abs_elevsc
self._df.loc[pos_elevsc_ind, 'SOU_H2OD'] *= abs_elevsc
self._df.loc[pos_elevsc_ind, 'REC_H2OD'] *= abs_elevsc
self._df.loc[pos_coordsc_ind, 'SOU_X'] *= abs_coordsc
self._df.loc[pos_coordsc_ind, 'SOU_Y'] *= abs_coordsc
self._df.loc[pos_coordsc_ind, 'REC_X'] *= abs_coordsc
self._df.loc[pos_coordsc_ind, 'REC_Y'] *= abs_coordsc
self._df.loc[pos_coordsc_ind, 'CDP_X'] *= abs_coordsc
self._df.loc[pos_coordsc_ind, 'CDP_Y'] *= abs_coordsc
def _apply_scalars_before_packing(self):
""" Apply elevation and coordinate scalars before packing. """
# zero should be treated as one
self._df.replace({'ELEVSC', 0}, 1, inplace=True)
self._df.replace({'COORDSC', 0}, 1, inplace=True)
# take the absolute value of the scalars
abs_elevsc = abs(self._df.ELEVSC)
abs_coordsc = abs(self._df.COORDSC)
# for unpacking: if negative, to be used as a divisor
# so, multiply before packing
neg_elevsc_ind = self._df.ELEVSC < 0
neg_coordsc_ind = self._df.COORDSC < 0
self._df.loc[neg_elevsc_ind, 'REC_ELEV'] *= abs_elevsc
self._df.loc[neg_elevsc_ind, 'SOU_ELEV'] *= abs_elevsc
self._df.loc[neg_elevsc_ind, 'DEPTH'] *= abs_elevsc
self._df.loc[neg_elevsc_ind, 'REC_DATUM'] *= abs_elevsc
self._df.loc[neg_elevsc_ind, 'SOU_DATUM'] *= abs_elevsc
self._df.loc[neg_elevsc_ind, 'SOU_H2OD'] *= abs_elevsc
self._df.loc[neg_elevsc_ind, 'REC_H2OD'] *= abs_elevsc
self._df.loc[neg_coordsc_ind, 'SOU_X'] *= abs_coordsc
self._df.loc[neg_coordsc_ind, 'SOU_Y'] *= abs_coordsc
self._df.loc[neg_coordsc_ind, 'REC_X'] *= abs_coordsc
self._df.loc[neg_coordsc_ind, 'REC_Y'] *= abs_coordsc
self._df.loc[neg_coordsc_ind, 'CDP_X'] *= abs_coordsc
self._df.loc[neg_coordsc_ind, 'CDP_Y'] *= abs_coordsc
# for unpacking: if positive, to be used as a multiplier
# so, divide before packing
pos_elevsc_ind = self._df.ELEVSC > 0
pos_coordsc_ind = self._df.COORDSC > 0
self._df.loc[pos_elevsc_ind, 'REC_ELEV'] /= abs_elevsc
self._df.loc[pos_elevsc_ind, 'SOU_ELEV'] /= abs_elevsc
self._df.loc[pos_elevsc_ind, 'DEPTH'] /= abs_elevsc
self._df.loc[pos_elevsc_ind, 'REC_DATUM'] /= abs_elevsc
self._df.loc[pos_elevsc_ind, 'SOU_DATUM'] /= abs_elevsc
self._df.loc[pos_elevsc_ind, 'SOU_H2OD'] /= abs_elevsc
self._df.loc[pos_elevsc_ind, 'REC_H2OD'] /= abs_elevsc
self._df.loc[pos_coordsc_ind, 'SOU_X'] /= abs_coordsc
self._df.loc[pos_coordsc_ind, 'SOU_Y'] /= abs_coordsc
self._df.loc[pos_coordsc_ind, 'REC_X'] /= abs_coordsc
self._df.loc[pos_coordsc_ind, 'REC_Y'] /= abs_coordsc
self._df.loc[pos_coordsc_ind, 'CDP_X'] /= abs_coordsc
self._df.loc[pos_coordsc_ind, 'CDP_Y'] /= abs_coordsc
@property
def TRACENO(self):
return self._df.TRACENO
@TRACENO.setter
def TRACENO(self, val):
self._df.loc[:, 'TRACENO'] = val
@property
def FFID(self):
return self._df.FFID
@FFID.setter
def FFID(self, val):
self._df.loc[:, 'FFID'] = val
@property
def CHAN(self):
return self._df.CHAN
@CHAN.setter
def CHAN(self, val):
self._df.loc[:, 'CHAN'] = val
@property
def SOU_X(self):
return self._df.SOU_X
@SOU_X.setter
def SOU_X(self, val):
self._df.loc[:, 'SOU_X'] = val
@property
def SOU_Y(self):
return self._df.SOU_Y
@SOU_Y.setter
def SOU_Y(self, val):
self._df.loc[:, 'SOU_Y'] = val
@property
def REC_X(self):
return self._df.REC_X
@REC_X.setter
def REC_X(self, val):
self._df.loc[:, 'REC_X'] = val
@property
def REC_Y(self):
return self._df.REC_Y
@REC_Y.setter
def REC_Y(self, val):
self._df.loc[:, 'REC_Y'] = val
@property
def CDP_X(self):
return self._df.CDP_X
@CDP_X.setter
def CDP_X(self, val):
self._df.loc[:, 'CDP_X'] = val
@property
def CDP_Y(self):
return self._df.CDP_Y
@CDP_Y.setter
def CDP_Y(self, val):
self._df.loc[:, 'CDP_Y'] = val
@property
def CDP(self):
return self._df.CDP
@CDP.setter
def CDP(self, val):
self._df.loc[:, 'CDP'] = val
@property
def OFFSET(self):
return self._df.OFFSET
@OFFSET.setter
def OFFSET(self, val):
self._df.loc[:, 'OFFSET'] = val
@property
def REC_ELEV(self):
return self._df.REC_ELEV
@REC_ELEV.setter
def REC_ELEV(self, val):
self._df.loc[:, 'REC_ELEV'] = val
@property
def SOU_ELEV(self):
return self._df.SOU_ELEV
@SOU_ELEV.setter
def SOU_ELEV(self, val):
self._df.loc[:, 'SOU_ELEV'] = val
@property
def ELEVSC(self):
return self._df.ELEVSC
@ELEVSC.setter
def ELEVSC(self, val):
self._df.loc[:, 'ELEVSC'] = val
@property
def COORDSC(self):
return self._df.COORDSC
@COORDSC.setter
def COORDSC(self, val):
self._df.loc[:, 'COORDSC'] = val
@property
def YEAR(self):
return self._df.YEAR
@YEAR.setter
def YEAR(self, val):
self._df.loc[:, 'YEAR'] = val
@property
def DAY(self):
return self._df.DAY
@DAY.setter
def DAY(self, val):
self._df.loc[:, 'DAY'] = val
@property
def HOUR(self):
return self._df.HOUR
@HOUR.setter
def HOUR(self, val):
self._df.loc[:, 'HOUR'] = val
@property
def MINUTE(self):
return self._df.MINUTE
@MINUTE.setter
def MINUTE(self, val):
self._df.loc[:, 'MINUTE'] = val
@property
def SECOND(self):
return self._df.SECOND
@SECOND.setter
def SECOND(self, val):
self._df.loc[:, 'SECOND'] = val
| [
"philoseismos.segy.gfunc.grab_endiannes",
"numpy.empty",
"philoseismos.segy.gfunc.grab_sample_format",
"struct.unpack",
"philoseismos.segy.gfunc.grab_trace_length",
"philoseismos.segy.gfunc.grab_number_of_traces"
] | [((618, 643), 'philoseismos.segy.gfunc.grab_endiannes', 'gfunc.grab_endiannes', (['sgy'], {}), '(sgy)\n', (638, 643), False, 'from philoseismos.segy import gfunc\n'), ((661, 693), 'philoseismos.segy.gfunc.grab_number_of_traces', 'gfunc.grab_number_of_traces', (['sgy'], {}), '(sgy)\n', (688, 693), False, 'from philoseismos.segy import gfunc\n'), ((761, 789), 'philoseismos.segy.gfunc.grab_trace_length', 'gfunc.grab_trace_length', (['sgy'], {}), '(sgy)\n', (784, 789), False, 'from philoseismos.segy import gfunc\n'), ((930, 970), 'numpy.empty', 'np.empty', ([], {'shape': '(nt, 90)', 'dtype': 'np.int32'}), '(shape=(nt, 90), dtype=np.int32)\n', (938, 970), True, 'import numpy as np\n'), ((711, 740), 'philoseismos.segy.gfunc.grab_sample_format', 'gfunc.grab_sample_format', (['sgy'], {}), '(sgy)\n', (735, 740), False, 'from philoseismos.segy import gfunc\n'), ((1127, 1179), 'struct.unpack', 'struct.unpack', (['(endian + const.THFS)', 'raw_header[:232]'], {}), '(endian + const.THFS, raw_header[:232])\n', (1140, 1179), False, 'import struct\n')] |
input_names = {'TL': '../examples/large_deformation/hyperelastic.py',
'UL': '../examples/large_deformation/hyperelastic_ul.py',
'ULM': '../examples/large_deformation/hyperelastic_ul_up.py'}
output_name_trunk = 'test_hyperelastic_'
from sfepy.base.testing import TestCommon
from tests_basic import NLSStatus
class Test(TestCommon):
@staticmethod
def from_conf(conf, options):
return Test(conf = conf, options = options)
def test_solution(self):
from sfepy.base.base import Struct
from sfepy.base.conf import ProblemConf, get_standard_keywords
from sfepy.applications import solve_pde, assign_standard_hooks
import numpy as nm
import os.path as op
solutions = {}
ok = True
for hp, pb_filename in input_names.iteritems():
required, other = get_standard_keywords()
input_name = op.join(op.dirname(__file__), pb_filename)
test_conf = ProblemConf.from_file(input_name, required, other)
name = output_name_trunk + hp
solver_options = Struct(output_filename_trunk=name,
output_format='vtk',
save_ebc=False, save_ebc_nodes=False,
save_regions=False,
save_regions_as_groups=False,
save_field_meshes=False,
solve_not=False)
assign_standard_hooks(self, test_conf.options.get, test_conf)
self.report( 'hyperelastic formulation: %s' % (hp, ) )
status = NLSStatus(conditions=[])
pb, state = solve_pde(test_conf,
solver_options,
nls_status=status,
output_dir=self.options.out_dir,
step_hook=self.step_hook,
post_process_hook=self.post_process_hook,
post_process_hook_final=self.post_process_hook_final)
converged = status.condition == 0
ok = ok and converged
solutions[hp] = state.get_parts()['u']
self.report('%s solved' % input_name)
rerr = 1.0e-3
aerr = nm.linalg.norm(solutions['TL'], ord=None) * rerr
self.report('allowed error: rel = %e, abs = %e' % (rerr, aerr))
ok = ok and self.compare_vectors(solutions['TL'], solutions['UL'],
label1='TLF',
label2='ULF',
allowed_error=rerr)
ok = ok and self.compare_vectors(solutions['UL'], solutions['ULM'],
label1='ULF',
label2='ULF_mixed',
allowed_error=rerr)
return ok
| [
"sfepy.base.conf.get_standard_keywords",
"sfepy.base.base.Struct",
"sfepy.base.conf.ProblemConf.from_file",
"os.path.dirname",
"sfepy.applications.solve_pde",
"numpy.linalg.norm",
"sfepy.applications.assign_standard_hooks",
"tests_basic.NLSStatus"
] | [((871, 894), 'sfepy.base.conf.get_standard_keywords', 'get_standard_keywords', ([], {}), '()\n', (892, 894), False, 'from sfepy.base.conf import ProblemConf, get_standard_keywords\n'), ((987, 1037), 'sfepy.base.conf.ProblemConf.from_file', 'ProblemConf.from_file', (['input_name', 'required', 'other'], {}), '(input_name, required, other)\n', (1008, 1037), False, 'from sfepy.base.conf import ProblemConf, get_standard_keywords\n'), ((1110, 1303), 'sfepy.base.base.Struct', 'Struct', ([], {'output_filename_trunk': 'name', 'output_format': '"""vtk"""', 'save_ebc': '(False)', 'save_ebc_nodes': '(False)', 'save_regions': '(False)', 'save_regions_as_groups': '(False)', 'save_field_meshes': '(False)', 'solve_not': '(False)'}), "(output_filename_trunk=name, output_format='vtk', save_ebc=False,\n save_ebc_nodes=False, save_regions=False, save_regions_as_groups=False,\n save_field_meshes=False, solve_not=False)\n", (1116, 1303), False, 'from sfepy.base.base import Struct\n'), ((1524, 1585), 'sfepy.applications.assign_standard_hooks', 'assign_standard_hooks', (['self', 'test_conf.options.get', 'test_conf'], {}), '(self, test_conf.options.get, test_conf)\n', (1545, 1585), False, 'from sfepy.applications import solve_pde, assign_standard_hooks\n'), ((1676, 1700), 'tests_basic.NLSStatus', 'NLSStatus', ([], {'conditions': '[]'}), '(conditions=[])\n', (1685, 1700), False, 'from tests_basic import NLSStatus\n'), ((1726, 1946), 'sfepy.applications.solve_pde', 'solve_pde', (['test_conf', 'solver_options'], {'nls_status': 'status', 'output_dir': 'self.options.out_dir', 'step_hook': 'self.step_hook', 'post_process_hook': 'self.post_process_hook', 'post_process_hook_final': 'self.post_process_hook_final'}), '(test_conf, solver_options, nls_status=status, output_dir=self.\n options.out_dir, step_hook=self.step_hook, post_process_hook=self.\n post_process_hook, post_process_hook_final=self.post_process_hook_final)\n', (1735, 1946), False, 'from sfepy.applications import solve_pde, assign_standard_hooks\n'), ((2362, 2403), 'numpy.linalg.norm', 'nm.linalg.norm', (["solutions['TL']"], {'ord': 'None'}), "(solutions['TL'], ord=None)\n", (2376, 2403), True, 'import numpy as nm\n'), ((928, 948), 'os.path.dirname', 'op.dirname', (['__file__'], {}), '(__file__)\n', (938, 948), True, 'import os.path as op\n')] |
import datetime
import glob
import json
import multiprocessing
import os
import pickle
import sys
import warnings
from collections import Counter, defaultdict
from string import digits
import matplotlib.pyplot as plt
from joblib import Parallel, delayed
import numpy as np
import pandas as pd
from dateutil import parser
from nltk.corpus import stopwords
from nltk.corpus import wordnet as wn
from nltk.stem import WordNetLemmatizer
from nltk.tokenize import RegexpTokenizer
from nltk.sentiment.vader import SentimentIntensityAnalyzer
sys.path.insert(0, os.path.dirname(__file__) + '../2_helpers')
from decoder import decoder
num_cores = multiprocessing.cpu_count()
num_jobs = round(num_cores * 3 / 4)
DIR = os.path.dirname(__file__) + '../../3_Data/'
WNL = WordNetLemmatizer()
NLTK_STOPWORDS = set(stopwords.words('english'))
neg_words_f = glob.glob(DIR + 'model_data/negative-words.txt')[0]
pos_words_f = glob.glob(DIR + 'model_data/positive-words.txt')[0]
with open(neg_words_f, 'r', encoding = "ISO-8859-1") as f:
neg_words = [w.strip().replace('\n','') for w in f.readlines()]
with open(pos_words_f, 'r', encoding = "ISO-8859-1") as f:
pos_words = [w.strip().replace('\n','') for w in f.readlines()]
print(len(neg_words), neg_words[:10])
sid = SentimentIntensityAnalyzer()
def get_users():
user_files = glob.glob(DIR + 'user_tweets/' + 'user_*.json')
print('{} users'.format(len(user_files)))
if len(user_files) < 10: print('WRONG DIR?')
users = []
for user_file in user_files:
user = json.loads(open(user_file).readline(), object_hook=decoder)
users.append(user)
return users
def tokenize_text(text):
tokenizer = RegexpTokenizer(r'\w+')
return [WNL.lemmatize(i.lower()) for i in tokenizer.tokenize(text) if
i.lower() not in NLTK_STOPWORDS]
def was_user_correct(user, facts, transactions):
for tr in transactions:
if str(tr.user_id) == str(user.user_id):
transaction = tr
user.transactions = tr
transactions.remove(tr)
user.fact = transaction.fact
user.fact_text = transaction.text
user.fact_text_ts = transaction.timestamp
user.stance = 0 if transaction.stance == 'denying' else 1 if transaction.stance == 'supporting' else 2 if transaction.stance == 'comment' else 3
break
for fact in facts:
if fact.hash == transaction.fact:
user.text = transaction.text
if (str(fact.true) == '1' and transaction.stance == 'supporting') or (
str(fact.true) == '0' and transaction.stance == 'denying'):
user.was_correct = 1
elif(str(fact.true) == '1' and transaction.stance == 'denying') or \
(str(fact.true) == '0' and transaction.stance == 'supporting'):
user.was_correct = 0
else:
user.was_correct = -1
print(fact.true, transaction.stance, user.was_correct)
return user
def linguistic_f(user):
user_pos_words = 0
user_neg_words = 0
if not user.tweets: return user
for tweet in user.tweets:
for token in tokenize_text(tweet['text']):
if token in neg_words:
user_neg_words += 1
if token in pos_words:
user_pos_words += 1
if user.features is None: user.features = {}; print(user.user_id)
user.features['pos_words'] = user_pos_words
user.features['neg_words'] = user_neg_words
return user
# bias
assertives = ['think', 'believe', 'suppose', 'expect', 'imagine']
factives = ['know', 'realize', 'regret', 'forget', 'find out']
hedges = ['postulates', 'felt', 'likely', 'mainly', 'guess']
implicatives = ['manage', 'remember', 'bother', 'get', 'dare']
# subjectivity
wiki_Bias_Lexicon = ['apologetic', 'summer', 'advance', 'cornerstone']
negative = ['hypocricy', 'swindle', 'unacceptable', 'worse']
positive = ['steadiest', 'enjoyed', 'prominence', 'lucky']
subj_clues = ['better', 'heckle', 'grisly', 'defeat', 'peevish']
affective = ['disgust', 'anxious', 'revolt', 'guilt', 'confident']
def feature_user_tweet_sentiment(user):
if not user.tweets: return user
tweet_sents = []
for tweet in user.tweets:
ss = sid.polarity_scores(tweet['text'])
tweet_sents.append(ss['compound'])
#density, _ = np.histogram(tweet_sents, bins=bins, density=True)
#user.sent_tweets_density = density / density.sum()
user.sent_tweets_avg = np.average(tweet_sents)
return user
def time_til_retweet(user):
print("Calculating avg time between original tweet and retweet per user")
user.avg_time_to_retweet = 0
if not user.tweets or len(user.tweets) < 1: return user
time_btw_rt = []
for tweet in user.tweets:
if not 'quoted_status' in tweet: continue
if not 'created_at' in tweet['quoted_status']: continue
date_original = parser.parse(tweet['quoted_status']['created_at'])
date_retweet = parser.parse(tweet['created_at'])
time_btw_rt.append(date_original - date_retweet)
if len(time_btw_rt) == 0: return user
average_timedelta = round(float((sum(time_btw_rt, datetime.timedelta(0)) / len(time_btw_rt)).seconds) / 60)
user.avg_time_to_retweet = average_timedelta
return user
def store_result(user):
with open(DIR + 'user_tweets/' + 'user_' + str(user.user_id) + '.json', 'w') as out_file:
out_file.write(json.dumps(user.__dict__, default=datetime_converter) + '\n')
def datetime_converter(o):
if isinstance(o, datetime):
return o.__str__()
def main():
wn.ensure_loaded()
users = get_users()
#users = [was_user_correct(user) for user in users]
#print("Linguistic features..")
#users = Parallel(n_jobs=num_jobs)(delayed(linguistic_f)(user) for user in users)
#print("Calculating tweet sentiment for each user")
users = Parallel(n_jobs=num_jobs)(delayed(feature_user_tweet_sentiment)(user) for user in users)
print("Avg time to retweet")
users = Parallel(n_jobs=num_jobs)(delayed(time_til_retweet)(user) for user in users)
print([u.sent_tweets_avg for u in users[:10]])
print([u.avg_time_to_retweet for u in users[:10]])
[store_result(user) for user in users]
if __name__ == "__main__":
main() | [
"nltk.tokenize.RegexpTokenizer",
"dateutil.parser.parse",
"numpy.average",
"nltk.sentiment.vader.SentimentIntensityAnalyzer",
"nltk.stem.WordNetLemmatizer",
"os.path.dirname",
"json.dumps",
"joblib.Parallel",
"datetime.timedelta",
"nltk.corpus.stopwords.words",
"glob.glob",
"nltk.corpus.wordne... | [((641, 668), 'multiprocessing.cpu_count', 'multiprocessing.cpu_count', ([], {}), '()\n', (666, 668), False, 'import multiprocessing\n'), ((763, 782), 'nltk.stem.WordNetLemmatizer', 'WordNetLemmatizer', ([], {}), '()\n', (780, 782), False, 'from nltk.stem import WordNetLemmatizer\n'), ((1263, 1291), 'nltk.sentiment.vader.SentimentIntensityAnalyzer', 'SentimentIntensityAnalyzer', ([], {}), '()\n', (1289, 1291), False, 'from nltk.sentiment.vader import SentimentIntensityAnalyzer\n'), ((712, 737), 'os.path.dirname', 'os.path.dirname', (['__file__'], {}), '(__file__)\n', (727, 737), False, 'import os\n'), ((804, 830), 'nltk.corpus.stopwords.words', 'stopwords.words', (['"""english"""'], {}), "('english')\n", (819, 830), False, 'from nltk.corpus import stopwords\n'), ((847, 895), 'glob.glob', 'glob.glob', (["(DIR + 'model_data/negative-words.txt')"], {}), "(DIR + 'model_data/negative-words.txt')\n", (856, 895), False, 'import glob\n'), ((913, 961), 'glob.glob', 'glob.glob', (["(DIR + 'model_data/positive-words.txt')"], {}), "(DIR + 'model_data/positive-words.txt')\n", (922, 961), False, 'import glob\n'), ((1328, 1375), 'glob.glob', 'glob.glob', (["(DIR + 'user_tweets/' + 'user_*.json')"], {}), "(DIR + 'user_tweets/' + 'user_*.json')\n", (1337, 1375), False, 'import glob\n'), ((1681, 1704), 'nltk.tokenize.RegexpTokenizer', 'RegexpTokenizer', (['"""\\\\w+"""'], {}), "('\\\\w+')\n", (1696, 1704), False, 'from nltk.tokenize import RegexpTokenizer\n'), ((4551, 4574), 'numpy.average', 'np.average', (['tweet_sents'], {}), '(tweet_sents)\n', (4561, 4574), True, 'import numpy as np\n'), ((5677, 5695), 'nltk.corpus.wordnet.ensure_loaded', 'wn.ensure_loaded', ([], {}), '()\n', (5693, 5695), True, 'from nltk.corpus import wordnet as wn\n'), ((555, 580), 'os.path.dirname', 'os.path.dirname', (['__file__'], {}), '(__file__)\n', (570, 580), False, 'import os\n'), ((4981, 5031), 'dateutil.parser.parse', 'parser.parse', (["tweet['quoted_status']['created_at']"], {}), "(tweet['quoted_status']['created_at'])\n", (4993, 5031), False, 'from dateutil import parser\n'), ((5055, 5088), 'dateutil.parser.parse', 'parser.parse', (["tweet['created_at']"], {}), "(tweet['created_at'])\n", (5067, 5088), False, 'from dateutil import parser\n'), ((5967, 5992), 'joblib.Parallel', 'Parallel', ([], {'n_jobs': 'num_jobs'}), '(n_jobs=num_jobs)\n', (5975, 5992), False, 'from joblib import Parallel, delayed\n'), ((6101, 6126), 'joblib.Parallel', 'Parallel', ([], {'n_jobs': 'num_jobs'}), '(n_jobs=num_jobs)\n', (6109, 6126), False, 'from joblib import Parallel, delayed\n'), ((5509, 5562), 'json.dumps', 'json.dumps', (['user.__dict__'], {'default': 'datetime_converter'}), '(user.__dict__, default=datetime_converter)\n', (5519, 5562), False, 'import json\n'), ((5993, 6030), 'joblib.delayed', 'delayed', (['feature_user_tweet_sentiment'], {}), '(feature_user_tweet_sentiment)\n', (6000, 6030), False, 'from joblib import Parallel, delayed\n'), ((6127, 6152), 'joblib.delayed', 'delayed', (['time_til_retweet'], {}), '(time_til_retweet)\n', (6134, 6152), False, 'from joblib import Parallel, delayed\n'), ((5243, 5264), 'datetime.timedelta', 'datetime.timedelta', (['(0)'], {}), '(0)\n', (5261, 5264), False, 'import datetime\n')] |
"""Functional tests for Unpack Op."""
import tensorflow.python.platform
import numpy as np
import tensorflow as tf
from tensorflow.python.kernel_tests import gradient_checker
class UnpackOpTest(tf.test.TestCase):
def testSimple(self):
np.random.seed(7)
for use_gpu in False, True:
with self.test_session(use_gpu=use_gpu):
for shape in (2,), (3,), (2, 3), (3, 2), (4, 3, 2):
data = np.random.randn(*shape)
# Convert data to a single tensorflow tensor
x = tf.constant(data)
# Unpack into a list of tensors
cs = tf.unpack(x, num=shape[0])
self.assertEqual(type(cs), list)
self.assertEqual(len(cs), shape[0])
cs = [c.eval() for c in cs]
self.assertAllEqual(cs, data)
def testGradients(self):
for use_gpu in False, True:
for shape in (2,), (3,), (2, 3), (3, 2), (4, 3, 2):
data = np.random.randn(*shape)
shapes = [shape[1:]] * shape[0]
for i in xrange(shape[0]):
with self.test_session(use_gpu=use_gpu):
x = tf.constant(data)
cs = tf.unpack(x, num=shape[0])
err = gradient_checker.ComputeGradientError(x, shape, cs[i],
shapes[i])
self.assertLess(err, 1e-6)
def testInferNum(self):
with self.test_session():
for shape in (2,), (3,), (2, 3), (3, 2), (4, 3, 2):
x = tf.placeholder(np.float32, shape=shape)
cs = tf.unpack(x)
self.assertEqual(type(cs), list)
self.assertEqual(len(cs), shape[0])
def testCannotInferNum(self):
x = tf.placeholder(np.float32)
with self.assertRaisesRegexp(
ValueError, r'Cannot infer num from shape TensorShape\(None\)'):
tf.unpack(x)
if __name__ == '__main__':
tf.test.main()
| [
"tensorflow.test.main",
"tensorflow.unpack",
"numpy.random.seed",
"numpy.random.randn",
"tensorflow.constant",
"tensorflow.placeholder",
"tensorflow.python.kernel_tests.gradient_checker.ComputeGradientError"
] | [((1825, 1839), 'tensorflow.test.main', 'tf.test.main', ([], {}), '()\n', (1837, 1839), True, 'import tensorflow as tf\n'), ((246, 263), 'numpy.random.seed', 'np.random.seed', (['(7)'], {}), '(7)\n', (260, 263), True, 'import numpy as np\n'), ((1641, 1667), 'tensorflow.placeholder', 'tf.placeholder', (['np.float32'], {}), '(np.float32)\n', (1655, 1667), True, 'import tensorflow as tf\n'), ((1781, 1793), 'tensorflow.unpack', 'tf.unpack', (['x'], {}), '(x)\n', (1790, 1793), True, 'import tensorflow as tf\n'), ((915, 938), 'numpy.random.randn', 'np.random.randn', (['*shape'], {}), '(*shape)\n', (930, 938), True, 'import numpy as np\n'), ((1449, 1488), 'tensorflow.placeholder', 'tf.placeholder', (['np.float32'], {'shape': 'shape'}), '(np.float32, shape=shape)\n', (1463, 1488), True, 'import tensorflow as tf\n'), ((1502, 1514), 'tensorflow.unpack', 'tf.unpack', (['x'], {}), '(x)\n', (1511, 1514), True, 'import tensorflow as tf\n'), ((420, 443), 'numpy.random.randn', 'np.random.randn', (['*shape'], {}), '(*shape)\n', (435, 443), True, 'import numpy as np\n'), ((513, 530), 'tensorflow.constant', 'tf.constant', (['data'], {}), '(data)\n', (524, 530), True, 'import tensorflow as tf\n'), ((588, 614), 'tensorflow.unpack', 'tf.unpack', (['x'], {'num': 'shape[0]'}), '(x, num=shape[0])\n', (597, 614), True, 'import tensorflow as tf\n'), ((1081, 1098), 'tensorflow.constant', 'tf.constant', (['data'], {}), '(data)\n', (1092, 1098), True, 'import tensorflow as tf\n'), ((1116, 1142), 'tensorflow.unpack', 'tf.unpack', (['x'], {'num': 'shape[0]'}), '(x, num=shape[0])\n', (1125, 1142), True, 'import tensorflow as tf\n'), ((1161, 1226), 'tensorflow.python.kernel_tests.gradient_checker.ComputeGradientError', 'gradient_checker.ComputeGradientError', (['x', 'shape', 'cs[i]', 'shapes[i]'], {}), '(x, shape, cs[i], shapes[i])\n', (1198, 1226), False, 'from tensorflow.python.kernel_tests import gradient_checker\n')] |
import os.path as osp
from typing import Callable, Optional
import numpy as np
import torch
from torch_geometric.data import Data, InMemoryDataset, download_url
class GemsecDeezer(InMemoryDataset):
r"""The Deezer User Network datasets introduced in the
`"GEMSEC: Graph Embedding with Self Clustering"
<https://arxiv.org/abs/1802.03997>`_ paper.
Nodes represent Deezer user and edges are mutual friendships.
The task is multi-label multi-class node classification about
the genres liked by the users.
Args:
root (string): Root directory where the dataset should be saved.
name (string): The name of the dataset (:obj:`"HU"`, :obj:`"HR"`,
:obj:`"RO"`).
transform (callable, optional): A function/transform that takes in an
:obj:`torch_geometric.data.Data` object and returns a transformed
version. The data object will be transformed before every access.
(default: :obj:`None`)
pre_transform (callable, optional): A function/transform that takes in
an :obj:`torch_geometric.data.Data` object and returns a
transformed version. The data object will be transformed before
being saved to disk. (default: :obj:`None`)
"""
url = 'https://graphmining.ai/datasets/ptg/gemsec'
def __init__(self, root: str, name: str,
transform: Optional[Callable] = None,
pre_transform: Optional[Callable] = None):
self.name = name
assert self.name in ['HU', 'HR', 'RO']
super().__init__(root, transform, pre_transform)
self.data, self.slices = torch.load(self.processed_paths[0])
@property
def raw_dir(self) -> str:
return osp.join(self.root, self.name, 'raw')
@property
def processed_dir(self) -> str:
return osp.join(self.root, self.name, 'processed')
@property
def raw_file_names(self) -> str:
return f'{self.name}.npz'
@property
def processed_file_names(self) -> str:
return 'data.pt'
def download(self):
download_url(osp.join(self.url, self.name + '.npz'), self.raw_dir)
def process(self):
data = np.load(self.raw_paths[0], 'r', allow_pickle=True)
y = torch.from_numpy(data['target']).to(torch.long)
edge_index = torch.from_numpy(data['edges']).to(torch.long)
edge_index = edge_index.t().contiguous()
data = Data(y=y, edge_index=edge_index)
if self.pre_transform is not None:
data = self.pre_transform(data)
torch.save(self.collate([data]), self.processed_paths[0])
| [
"numpy.load",
"torch.load",
"torch_geometric.data.Data",
"os.path.join",
"torch.from_numpy"
] | [((1648, 1683), 'torch.load', 'torch.load', (['self.processed_paths[0]'], {}), '(self.processed_paths[0])\n', (1658, 1683), False, 'import torch\n'), ((1744, 1781), 'os.path.join', 'osp.join', (['self.root', 'self.name', '"""raw"""'], {}), "(self.root, self.name, 'raw')\n", (1752, 1781), True, 'import os.path as osp\n'), ((1848, 1891), 'os.path.join', 'osp.join', (['self.root', 'self.name', '"""processed"""'], {}), "(self.root, self.name, 'processed')\n", (1856, 1891), True, 'import os.path as osp\n'), ((2200, 2250), 'numpy.load', 'np.load', (['self.raw_paths[0]', '"""r"""'], {'allow_pickle': '(True)'}), "(self.raw_paths[0], 'r', allow_pickle=True)\n", (2207, 2250), True, 'import numpy as np\n'), ((2444, 2476), 'torch_geometric.data.Data', 'Data', ([], {'y': 'y', 'edge_index': 'edge_index'}), '(y=y, edge_index=edge_index)\n', (2448, 2476), False, 'from torch_geometric.data import Data, InMemoryDataset, download_url\n'), ((2107, 2145), 'os.path.join', 'osp.join', (['self.url', "(self.name + '.npz')"], {}), "(self.url, self.name + '.npz')\n", (2115, 2145), True, 'import os.path as osp\n'), ((2263, 2295), 'torch.from_numpy', 'torch.from_numpy', (["data['target']"], {}), "(data['target'])\n", (2279, 2295), False, 'import torch\n'), ((2332, 2363), 'torch.from_numpy', 'torch.from_numpy', (["data['edges']"], {}), "(data['edges'])\n", (2348, 2363), False, 'import torch\n')] |
#!/usr/bin/env python3
import math
import re
import sys
import subprocess
import numpy as np
from PIL import Image, ImageOps
# 1x icons are 32x28 in dimension
ICON_ASPECT = 32/28
class IconGrid:
def __init__(self, specfile):
self.groups = self.read_spec(specfile)
def read_spec(self, specfile):
"""
Returns a dict (x, y) -> name where x,y are row/column indexes (not pixels).
"""
# [ [images, {(x, y) -> name}, numrows], ...]
# [name, [image, ...], {(x, y): iconname, ...}, numrows]
groups = []
for line in open(specfile).readlines():
line = line.strip()
if not line:
continue
if line.startswith('#<'):
filenames = line[3:].strip().split()
icons = {}
x = y = 0
images = [self.load_image(fname) for fname in filenames]
if len(groups) > 0 and len(images) != len(groups[-1][0]):
print(f'ERROR: group {len(groups)+1} has inconsistent number of input files')
sys.exit(1)
group = [images, icons, 1]
groups.append(group)
elif line.startswith('#|'):
y += 1
x = 0
group[-1] += 1
elif not line.startswith('#'):
icons[(x, y)] = line
x += 1
return groups
def load_image(self, fname):
"""
Loads an image, and inverts all but the alpha channel, effectively converting
black input icons to white.
"""
img = Image.open(fname)
buf = np.array(img)
rgb = buf[:, :, :3]
a = buf[:, :, 3]
ivt = np.dstack((255 - rgb, a))
newimg = Image.fromarray(ivt)
m = re.search(r'(@[\d.]+x)', fname)
newimg.suffix = m.group(1) if m else ''
return newimg
def generate(self, outname):
# Total number of icons across all groups
count = sum(len(group[1]) for group in self.groups)
# First pass to create individual images for each DPI
outputs = []
for (images, icons, nrows) in self.groups:
for img in images:
icon_h = int(img.height / nrows)
icon_w = int(icon_h * ICON_ASPECT)
all_cols = math.ceil(math.sqrt(count))
all_rows = math.ceil(count / all_cols)
outimg = Image.new('RGBA', (all_cols * icon_w, all_rows * icon_h))
outputs.append((outimg, icon_w, icon_h, all_cols))
# We assume (i.e. require) all groups use the same icon resolutions
break
luarows = []
nimg = 0
for (images, icons, nrows) in self.groups:
for (srccol, srcrow), name in icons.items():
for nout, (srcimg, (dstimg, icon_w, icon_h, all_cols)) in enumerate(zip(images, outputs)):
dstcol = nimg % all_cols
dstrow = int(nimg / all_cols)
sx = srccol * icon_w
sy = srcrow * icon_h
dx = dstcol * icon_w
dy = dstrow * icon_h
dstimg.alpha_composite(srcimg, (dx, dy), (sx, sy, sx + icon_w, sy + icon_h))
if nout == 0:
if dstcol == 0:
luarows.append([])
luarows[-1].append(name)
# Useful for debugging: output individual icons as files
if True:
icon = Image.new('RGBA', (icon_w, icon_h))
icon.alpha_composite(srcimg, (0, 0), (sx, sy, sx + icon_w, sy + icon_h))
icon.save('individual/{}.png'.format(name))
nimg += 1
outw = max(outimg.width for outimg, *_ in outputs)
outh = sum(outimg.height for outimg, *_ in outputs)
pack = Image.new('RGBA', (outw, outh))
y = 0
for outimg, *_ in outputs:
pack.alpha_composite(outimg, (0, y), (0, 0))
y = y + outimg.height
outfile = f'../../img/{outname}'
pack.save(outfile)
subprocess.run(['pngcrush', '-ow', outfile])
with open('articons.lua', 'w') as luaout:
luaout.write('articons.rows = {\n')
for row in luarows:
luaout.write(' {\n')
for name in row:
luaout.write(f" '{name}',\n")
luaout.write(' },\n')
luaout.write('}\n')
if __name__ == '__main__':
grid = IconGrid('artnames.txt')
grid.generate('articulations.png')
| [
"numpy.dstack",
"subprocess.run",
"PIL.Image.new",
"math.sqrt",
"math.ceil",
"PIL.Image.open",
"numpy.array",
"PIL.Image.fromarray",
"re.search",
"sys.exit"
] | [((1680, 1697), 'PIL.Image.open', 'Image.open', (['fname'], {}), '(fname)\n', (1690, 1697), False, 'from PIL import Image, ImageOps\n'), ((1713, 1726), 'numpy.array', 'np.array', (['img'], {}), '(img)\n', (1721, 1726), True, 'import numpy as np\n'), ((1797, 1822), 'numpy.dstack', 'np.dstack', (['(255 - rgb, a)'], {}), '((255 - rgb, a))\n', (1806, 1822), True, 'import numpy as np\n'), ((1841, 1861), 'PIL.Image.fromarray', 'Image.fromarray', (['ivt'], {}), '(ivt)\n', (1856, 1861), False, 'from PIL import Image, ImageOps\n'), ((1875, 1906), 're.search', 're.search', (['"""(@[\\\\d.]+x)"""', 'fname'], {}), "('(@[\\\\d.]+x)', fname)\n", (1884, 1906), False, 'import re\n'), ((4086, 4117), 'PIL.Image.new', 'Image.new', (['"""RGBA"""', '(outw, outh)'], {}), "('RGBA', (outw, outh))\n", (4095, 4117), False, 'from PIL import Image, ImageOps\n'), ((4341, 4385), 'subprocess.run', 'subprocess.run', (["['pngcrush', '-ow', outfile]"], {}), "(['pngcrush', '-ow', outfile])\n", (4355, 4385), False, 'import subprocess\n'), ((2482, 2509), 'math.ceil', 'math.ceil', (['(count / all_cols)'], {}), '(count / all_cols)\n', (2491, 2509), False, 'import math\n'), ((2536, 2593), 'PIL.Image.new', 'Image.new', (['"""RGBA"""', '(all_cols * icon_w, all_rows * icon_h)'], {}), "('RGBA', (all_cols * icon_w, all_rows * icon_h))\n", (2545, 2593), False, 'from PIL import Image, ImageOps\n'), ((1136, 1147), 'sys.exit', 'sys.exit', (['(1)'], {}), '(1)\n', (1144, 1147), False, 'import sys\n'), ((2436, 2452), 'math.sqrt', 'math.sqrt', (['count'], {}), '(count)\n', (2445, 2452), False, 'import math\n'), ((3709, 3744), 'PIL.Image.new', 'Image.new', (['"""RGBA"""', '(icon_w, icon_h)'], {}), "('RGBA', (icon_w, icon_h))\n", (3718, 3744), False, 'from PIL import Image, ImageOps\n')] |
# -*- coding: utf-8 -*-
"""
Created on Sun Dec 1 13:43:31 2019
@author: Mateo
"""
import numpy as np
import HARK.ConsumptionSaving.ConsPortfolioModel as cpm
# Plotting tools
import matplotlib.pyplot as plt
import seaborn
# %% Set up figure path
import sys,os
# Determine if this is being run as a standalone script
if __name__ == '__main__':
# Running as a script
my_file_path = os.path.abspath("../")
else:
# Running from do_ALL
my_file_path = os.path.dirname(os.path.abspath("do_ALL.py"))
my_file_path = os.path.join(my_file_path,"Code/Python/")
FigPath = os.path.join(my_file_path,"Figures/")
# %% import Calibration
sys.path.append(my_file_path)
from Calibration.params import dict_portfolio, norm_factor
# %% Setup
# Path to fortran output
pathFort = os.path.join(my_file_path,"../Fortran/")
# Asset grid
npoints = 401
agrid = np.linspace(4,npoints+3,npoints)
# number of years
nyears = dict_portfolio['T_cycle']
# Initialize consumption, value, and share matrices
# (rows = age, cols = assets)
cons = np.zeros((nyears, npoints))
val = np.zeros((nyears, npoints))
share = np.zeros((nyears, npoints))
# %% Read and split policy functions
for year in range(nyears):
y = year + 1
if y < 10:
ystring = '0' + str(y)
else:
ystring = str(y)
rawdata = np.loadtxt(pathFort + 'year' + ystring + '.txt')
share[year,:] = rawdata[range(npoints)]
cons[year,:] = rawdata[range(npoints,2*npoints)]
val[year,:] = rawdata[range(2*npoints,3*npoints)]
# %% Compute HARK's policy functions and store them in the same format
agent = cpm.PortfolioConsumerType(**dict_portfolio)
agent.solve()
# CGM's fortran code does not output the policy functions for the final period.
# thus len(agent.solve) = nyears + 1
# Initialize HARK's counterparts to the policy function matrices
h_cons = np.zeros((nyears, npoints))
h_share = np.zeros((nyears, npoints))
# Fill with HARK's interpolated policy function at the required points
for year in range(nyears):
h_cons[year,:] = agent.solution[year].cFuncAdj(agrid/norm_factor[year])*norm_factor[year]
h_share[year,:] = agent.solution[year].ShareFuncAdj(agrid/norm_factor[year])
# %% Compare the results
cons_error = h_cons - cons
share_error = h_share - share
## Heatmaps
# Consumption
# Find max consumption (for the color map)
cmax = max(np.max(h_cons),np.max(cons))
f, axes = plt.subplots(1, 3, figsize=(10, 4), sharex=True)
seaborn.despine(left=True)
seaborn.heatmap(h_cons, ax = axes[0], vmin = 0, vmax = cmax)
axes[0].set_title('HARK')
axes[0].set_xlabel('Assets', labelpad = 10)
axes[0].set_ylabel('Age')
seaborn.heatmap(cons, ax = axes[1], vmin = 0, vmax = cmax)
axes[1].set_title('CGM')
axes[1].set_xlabel('Assets', labelpad = 10)
axes[1].set_ylabel('Age')
seaborn.heatmap(cons_error, ax = axes[2], center = 0)
axes[2].set_title('HARK - CGM')
axes[2].set_xlabel('Assets', labelpad = 10)
axes[2].set_ylabel('Age')
f.suptitle('$C(\cdot)$')
f.tight_layout(rect=[0, 0.027, 1, 0.975])
f.subplots_adjust(top=0.85)
# Save figure
figname = 'Cons_Pol_Compare'
plt.savefig(os.path.join(FigPath, figname + '.png'))
plt.savefig(os.path.join(FigPath, figname + '.jpg'))
plt.savefig(os.path.join(FigPath, figname + '.pdf'))
plt.savefig(os.path.join(FigPath, figname + '.svg'))
plt.ioff()
plt.draw()
plt.pause(1)
# Risky share
f, axes = plt.subplots(1, 3, figsize=(10, 4), sharex=True)
seaborn.despine(left=True)
seaborn.heatmap(h_share, ax = axes[0], vmin = 0, vmax = 1)
axes[0].set_title('HARK')
axes[0].set_xlabel('Assets', labelpad = 10)
axes[0].set_ylabel('Age')
seaborn.heatmap(share, ax = axes[1], vmin = 0, vmax = 1)
axes[1].set_title('CGM')
axes[1].set_xlabel('Assets', labelpad = 10)
axes[1].set_ylabel('Age')
seaborn.heatmap(share_error, ax = axes[2], center = 0)
axes[2].set_title('HARK - CGM')
axes[2].set_xlabel('Assets', labelpad = 10)
axes[2].set_ylabel('Age')
f.suptitle('$S(\cdot)$')
f.tight_layout(rect=[0, 0.027, 1, 0.975])
f.subplots_adjust(top=0.85)
# Save figure
figname = 'RShare_Pol_Compare'
plt.savefig(os.path.join(FigPath, figname + '.png'))
plt.savefig(os.path.join(FigPath, figname + '.jpg'))
plt.savefig(os.path.join(FigPath, figname + '.pdf'))
plt.savefig(os.path.join(FigPath, figname + '.svg'))
plt.ioff()
plt.draw()
plt.pause(1) | [
"sys.path.append",
"os.path.abspath",
"seaborn.heatmap",
"matplotlib.pyplot.ioff",
"HARK.ConsumptionSaving.ConsPortfolioModel.PortfolioConsumerType",
"numpy.zeros",
"matplotlib.pyplot.subplots",
"seaborn.despine",
"matplotlib.pyplot.draw",
"numpy.max",
"numpy.loadtxt",
"numpy.linspace",
"mat... | [((590, 628), 'os.path.join', 'os.path.join', (['my_file_path', '"""Figures/"""'], {}), "(my_file_path, 'Figures/')\n", (602, 628), False, 'import sys, os\n'), ((653, 682), 'sys.path.append', 'sys.path.append', (['my_file_path'], {}), '(my_file_path)\n', (668, 682), False, 'import sys, os\n'), ((791, 832), 'os.path.join', 'os.path.join', (['my_file_path', '"""../Fortran/"""'], {}), "(my_file_path, '../Fortran/')\n", (803, 832), False, 'import sys, os\n'), ((868, 904), 'numpy.linspace', 'np.linspace', (['(4)', '(npoints + 3)', 'npoints'], {}), '(4, npoints + 3, npoints)\n', (879, 904), True, 'import numpy as np\n'), ((1046, 1073), 'numpy.zeros', 'np.zeros', (['(nyears, npoints)'], {}), '((nyears, npoints))\n', (1054, 1073), True, 'import numpy as np\n'), ((1082, 1109), 'numpy.zeros', 'np.zeros', (['(nyears, npoints)'], {}), '((nyears, npoints))\n', (1090, 1109), True, 'import numpy as np\n'), ((1118, 1145), 'numpy.zeros', 'np.zeros', (['(nyears, npoints)'], {}), '((nyears, npoints))\n', (1126, 1145), True, 'import numpy as np\n'), ((1629, 1672), 'HARK.ConsumptionSaving.ConsPortfolioModel.PortfolioConsumerType', 'cpm.PortfolioConsumerType', ([], {}), '(**dict_portfolio)\n', (1654, 1672), True, 'import HARK.ConsumptionSaving.ConsPortfolioModel as cpm\n'), ((1881, 1908), 'numpy.zeros', 'np.zeros', (['(nyears, npoints)'], {}), '((nyears, npoints))\n', (1889, 1908), True, 'import numpy as np\n'), ((1919, 1946), 'numpy.zeros', 'np.zeros', (['(nyears, npoints)'], {}), '((nyears, npoints))\n', (1927, 1946), True, 'import numpy as np\n'), ((2434, 2482), 'matplotlib.pyplot.subplots', 'plt.subplots', (['(1)', '(3)'], {'figsize': '(10, 4)', 'sharex': '(True)'}), '(1, 3, figsize=(10, 4), sharex=True)\n', (2446, 2482), True, 'import matplotlib.pyplot as plt\n'), ((2483, 2509), 'seaborn.despine', 'seaborn.despine', ([], {'left': '(True)'}), '(left=True)\n', (2498, 2509), False, 'import seaborn\n'), ((2511, 2565), 'seaborn.heatmap', 'seaborn.heatmap', (['h_cons'], {'ax': 'axes[0]', 'vmin': '(0)', 'vmax': 'cmax'}), '(h_cons, ax=axes[0], vmin=0, vmax=cmax)\n', (2526, 2565), False, 'import seaborn\n'), ((2669, 2721), 'seaborn.heatmap', 'seaborn.heatmap', (['cons'], {'ax': 'axes[1]', 'vmin': '(0)', 'vmax': 'cmax'}), '(cons, ax=axes[1], vmin=0, vmax=cmax)\n', (2684, 2721), False, 'import seaborn\n'), ((2824, 2873), 'seaborn.heatmap', 'seaborn.heatmap', (['cons_error'], {'ax': 'axes[2]', 'center': '(0)'}), '(cons_error, ax=axes[2], center=0)\n', (2839, 2873), False, 'import seaborn\n'), ((3334, 3344), 'matplotlib.pyplot.ioff', 'plt.ioff', ([], {}), '()\n', (3342, 3344), True, 'import matplotlib.pyplot as plt\n'), ((3345, 3355), 'matplotlib.pyplot.draw', 'plt.draw', ([], {}), '()\n', (3353, 3355), True, 'import matplotlib.pyplot as plt\n'), ((3356, 3368), 'matplotlib.pyplot.pause', 'plt.pause', (['(1)'], {}), '(1)\n', (3365, 3368), True, 'import matplotlib.pyplot as plt\n'), ((3394, 3442), 'matplotlib.pyplot.subplots', 'plt.subplots', (['(1)', '(3)'], {'figsize': '(10, 4)', 'sharex': '(True)'}), '(1, 3, figsize=(10, 4), sharex=True)\n', (3406, 3442), True, 'import matplotlib.pyplot as plt\n'), ((3443, 3469), 'seaborn.despine', 'seaborn.despine', ([], {'left': '(True)'}), '(left=True)\n', (3458, 3469), False, 'import seaborn\n'), ((3471, 3523), 'seaborn.heatmap', 'seaborn.heatmap', (['h_share'], {'ax': 'axes[0]', 'vmin': '(0)', 'vmax': '(1)'}), '(h_share, ax=axes[0], vmin=0, vmax=1)\n', (3486, 3523), False, 'import seaborn\n'), ((3627, 3677), 'seaborn.heatmap', 'seaborn.heatmap', (['share'], {'ax': 'axes[1]', 'vmin': '(0)', 'vmax': '(1)'}), '(share, ax=axes[1], vmin=0, vmax=1)\n', (3642, 3677), False, 'import seaborn\n'), ((3780, 3830), 'seaborn.heatmap', 'seaborn.heatmap', (['share_error'], {'ax': 'axes[2]', 'center': '(0)'}), '(share_error, ax=axes[2], center=0)\n', (3795, 3830), False, 'import seaborn\n'), ((4293, 4303), 'matplotlib.pyplot.ioff', 'plt.ioff', ([], {}), '()\n', (4301, 4303), True, 'import matplotlib.pyplot as plt\n'), ((4304, 4314), 'matplotlib.pyplot.draw', 'plt.draw', ([], {}), '()\n', (4312, 4314), True, 'import matplotlib.pyplot as plt\n'), ((4315, 4327), 'matplotlib.pyplot.pause', 'plt.pause', (['(1)'], {}), '(1)\n', (4324, 4327), True, 'import matplotlib.pyplot as plt\n'), ((394, 416), 'os.path.abspath', 'os.path.abspath', (['"""../"""'], {}), "('../')\n", (409, 416), False, 'import sys, os\n'), ((533, 575), 'os.path.join', 'os.path.join', (['my_file_path', '"""Code/Python/"""'], {}), "(my_file_path, 'Code/Python/')\n", (545, 575), False, 'import sys, os\n'), ((1337, 1385), 'numpy.loadtxt', 'np.loadtxt', (["(pathFort + 'year' + ystring + '.txt')"], {}), "(pathFort + 'year' + ystring + '.txt')\n", (1347, 1385), True, 'import numpy as np\n'), ((2395, 2409), 'numpy.max', 'np.max', (['h_cons'], {}), '(h_cons)\n', (2401, 2409), True, 'import numpy as np\n'), ((2410, 2422), 'numpy.max', 'np.max', (['cons'], {}), '(cons)\n', (2416, 2422), True, 'import numpy as np\n'), ((3133, 3172), 'os.path.join', 'os.path.join', (['FigPath', "(figname + '.png')"], {}), "(FigPath, figname + '.png')\n", (3145, 3172), False, 'import sys, os\n'), ((3186, 3225), 'os.path.join', 'os.path.join', (['FigPath', "(figname + '.jpg')"], {}), "(FigPath, figname + '.jpg')\n", (3198, 3225), False, 'import sys, os\n'), ((3239, 3278), 'os.path.join', 'os.path.join', (['FigPath', "(figname + '.pdf')"], {}), "(FigPath, figname + '.pdf')\n", (3251, 3278), False, 'import sys, os\n'), ((3292, 3331), 'os.path.join', 'os.path.join', (['FigPath', "(figname + '.svg')"], {}), "(FigPath, figname + '.svg')\n", (3304, 3331), False, 'import sys, os\n'), ((4092, 4131), 'os.path.join', 'os.path.join', (['FigPath', "(figname + '.png')"], {}), "(FigPath, figname + '.png')\n", (4104, 4131), False, 'import sys, os\n'), ((4145, 4184), 'os.path.join', 'os.path.join', (['FigPath', "(figname + '.jpg')"], {}), "(FigPath, figname + '.jpg')\n", (4157, 4184), False, 'import sys, os\n'), ((4198, 4237), 'os.path.join', 'os.path.join', (['FigPath', "(figname + '.pdf')"], {}), "(FigPath, figname + '.pdf')\n", (4210, 4237), False, 'import sys, os\n'), ((4251, 4290), 'os.path.join', 'os.path.join', (['FigPath', "(figname + '.svg')"], {}), "(FigPath, figname + '.svg')\n", (4263, 4290), False, 'import sys, os\n'), ((484, 512), 'os.path.abspath', 'os.path.abspath', (['"""do_ALL.py"""'], {}), "('do_ALL.py')\n", (499, 512), False, 'import sys, os\n')] |
"""
Written by <NAME> <<EMAIL>> 2017-2018
"""
import json
import os
from PIL import Image, ImageDraw, ImageFont
import imageio
import numpy as np
import progressbar
from skimage.transform import resize
import torch
from torch import nn
from torch.autograd import Variable
import matplotlib
# Disable Xwindows backend before importing matplotlib.pyplot
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import data
PERMUTATION = data.pixel_permutation().numpy()
UNPERMUTATION = np.argsort(PERMUTATION)
IMAGE_SIZE = [28,28]
def _clearline():
CURSOR_UP_ONE = '\x1b[1A'
ERASE_LINE = '\x1b[2K'
print(CURSOR_UP_ONE+ERASE_LINE+CURSOR_UP_ONE)
def visualizations(modeldir,val_loader,loss_fcn=nn.NLLLoss(),
n_collage=100,n_gif=10):
"""
Post-training visualizations:
1. Visualize backprop-to-input (static)
2. Save collages of lowest and highest-loss images with backprop-to-input
3. Make gif
"""
n_vis = max(n_collage,n_gif)
# Reload the saved net
model = torch.load(os.path.join(modeldir,'checkpoint'))
with open(os.path.join(modeldir,'params.json'),'r') as jsf:
params = json.load(jsf)
zoneout = params['zoneout']
cuda = params['cuda']
permuted = params['permuted']
if cuda:
model = model.cuda()
# Make path for saving images
savedir = os.path.join(modeldir,'input_grads')
if not os.path.isdir(savedir):
os.makedirs(savedir)
# Function to reshape img and grad, overlay and save
if permuted:
def reshape_img(x):
x = x[UNPERMUTATION]
return np.reshape(x,IMAGE_SIZE)
else:
def reshape_img(x):
return np.reshape(x,IMAGE_SIZE)
def overlay_grad(x,gx):
x, gx = np.squeeze(x), np.squeeze(gx)
# absolute value, normalize, contrast stretch and threshold
gx = np.abs(gx)
gx = (gx-np.min(gx))/(np.max(gx)-np.min(gx)+1e-10)
gx = gx**0.5
gx = 0.5*gx*(gx>(np.mean(gx)-np.std(gx))) \
+0.5*gx*(gx>(np.mean(gx)+np.std(gx)))
x = reshape_img(x)
gx = reshape_img(gx)
overlay = np.transpose([0.8*x+0.2*gx,gx,gx],[1,2,0])
# imageio.imwrite(os.path.join(savedir,str(file_id)+'.bmp'),overlay)
return overlay
# Run the validation set through the network
print('Running validation...')
def val_batch(x,y):
model.dropout.p = 0
hidden = model.init_hidden(x.data.size()[0])
if cuda:
hidden = hidden.cuda()
outputs = []
for i in range(x.size()[1]):
output,h_new = model(x[:,i],hidden)
# take expectation of zoneout
hidden = zoneout*hidden+(1-zoneout)*h_new
outputs.append(output.data.cpu().numpy())
loss = loss_fcn(output,y).data.cpu().numpy()
torch.max(output).backward()
return loss, outputs, x.grad.data.cpu().numpy()
# Find the best and worst n_vis examples
best_imgs = [None]*n_vis
best_grads = [None]*n_vis
best_losses = [np.inf]*n_vis
best_labels = [None]*n_vis
best_outputs = [None]*n_vis
replace_best = 0
wrst_imgs = [None]*n_vis
wrst_grads = [None]*n_vis
wrst_losses = [-np.inf]*n_vis
wrst_labels = [None]*n_vis
wrst_outputs = [None]*n_vis
replace_wrst = 0
bar = progressbar.ProgressBar()
# i = 0
for x,y in bar(val_loader):
# if i>n_vis:
# break
# i += 1
# print(i)
if cuda:
x,y = x.cuda(), y.cuda()
x,y = Variable(x,requires_grad=True), Variable(y)
loss,outputs,xgrad = val_batch(x,y)
loss = loss[0]
if loss<best_losses[replace_best]:
best_losses[replace_best] = loss
best_imgs[replace_best] = x.data.cpu().numpy()
best_grads[replace_best] = xgrad
best_labels[replace_best] = y.data.cpu().numpy()
best_outputs[replace_best] = outputs
replace_best = np.argmax(best_losses)
if loss>wrst_losses[replace_wrst]:
wrst_losses[replace_wrst] = loss
wrst_imgs[replace_wrst] = x.data.cpu().numpy()
wrst_grads[replace_wrst] = xgrad
wrst_labels[replace_wrst] = y.data.cpu().numpy()
wrst_outputs[replace_wrst] = outputs
replace_wrst = np.argmin(wrst_losses)
_clearline()
# Convert outputs from logsoftmax to regular softmax
best_outputs = [np.exp(o) for o in best_outputs]
wrst_outputs = [np.exp(o) for o in wrst_outputs]
# Make gifs of best and worst examples
gifdir = os.path.join(modeldir,'gifs')
if not os.path.isdir(gifdir):
os.makedirs(gifdir)
for i in range(n_gif):
make_gif(best_imgs[i],best_outputs[i],best_labels[i],
os.path.join(gifdir,'best'+str(i)+'.gif'))
make_gif(wrst_imgs[i], wrst_outputs[i], wrst_labels[i],
os.path.join(gifdir, 'worst'+str(i)+'.gif'))
# Make collages of best and worst examples
def frmt(output):
return ' '.join(['%.3f'%o for o in output[0].tolist()])
imgs = [overlay_grad(best_imgs[i],best_grads[i]) for i in range(n_collage)]
txt = ['Label: %i\nOutput: %s\nLoss: %.2f'
%(best_labels[i],frmt(best_outputs[i][-1]),best_losses[i])
for i in range(n_collage)]
collage(imgs,os.path.join(modeldir,'best.jpeg'),txt,fontsize=10)
imgs = [overlay_grad(wrst_imgs[i],wrst_grads[i]) for i in range(n_collage)]
txt = ['Label: %i\nOutput: %s\nLoss: %.2f'
%(wrst_labels[i],frmt(wrst_outputs[i][-1]),wrst_losses[i])
for i in range(n_collage)]
collage(imgs,os.path.join(modeldir,'worst.jpeg'),txt,fontsize=10)
def make_gif(img,output,label,saveto):
# Show image appear one pixel at a time (left)
# and the output from what it's seen so far (right)
img = np.squeeze(img)
img_gif = [100*np.ones(IMAGE_SIZE,dtype='uint8')]
for t,pixel_idx in enumerate(PERMUTATION):
r,c = pixel_idx//IMAGE_SIZE[0], pixel_idx%IMAGE_SIZE[0]
frame = np.copy(img_gif[-1]).astype('uint8')
frame[r,c] = np.squeeze(255*img[t]).astype('uint8')
img_gif.append(frame)
def bar_chart(out,lab):
fig = plt.figure(num=1,figsize=(4,4),dpi=70,facecolor='w',edgecolor='k')
x_rest = list(range(out.size))
x_label = x_rest.pop(lab)
y_rest = out.tolist()
y_label = y_rest.pop(lab)
_ = plt.bar(x_rest,y_rest,width=0.8,color='r')
_ = plt.bar(x_label,y_label,width=0.8,color='g')
plt.title('Outputs')
plt.rcParams.update({'font.size':10})
fig.tight_layout(pad=0)
fig.canvas.draw()
# now convert the plot to a numpy array
plot = np.fromstring(fig.canvas.tostring_rgb(), dtype=np.uint8, sep='')
plot = plot.reshape(fig.canvas.get_width_height()[::-1]+(3,))
plt.close(fig)
return plot
plot_gif = []
for i in range(output.shape[0]):
plot = bar_chart(np.squeeze(output[i]),np.squeeze(label))
plot_gif.append(plot.astype('uint8'))
# combine the image and plot
combined = []
for i,p in zip(img_gif,plot_gif):
if i.ndim==2:
i = np.repeat(i[:,:,np.newaxis],3,axis=2)
i = resize(i,[p.shape[0],int(i.shape[1]*p.shape[0]/i.shape[0])],order=0,
preserve_range=True,mode='constant').astype('uint8')
combined.append(np.concatenate((i,p),axis=1))
imageio.mimsave(saveto,combined,format='gif',loop=0,
duration=[0.005]*(len(combined)-1)+[1])
def collage(imgs,saveto,text=None,fontsize=10):
"""
Save a collage of images (e.g. to see highest vs lowest-loss examples)
"""
assert isinstance(imgs,list)
# assume >4:3 aspect ratio, figure out # of columns
columns = np.ceil(np.sqrt(len(imgs)*4/3))
while len(imgs)%columns!=0:
columns += 1
has_text = text is not None
if has_text:
assert isinstance(text,list)
assert all([type(t) is str for t in text])
assert len(imgs)==len(text)
lines = np.max([t.count('\n') for t in text])+1
else:
text = ['']*len(imgs)
row = []
result = []
for idx,(img,t) in enumerate(zip(imgs,text)):
img = resize(img,[280,280],order=0,preserve_range=True,mode='constant')
img = np.array(255*img, dtype='uint8')
img_size = img.shape
if img.ndim==2:
img = np.repeat(img[:,:,np.newaxis],3,axis=2)
if has_text:
img = np.concatenate((img,np.zeros((int(1.5*lines*fontsize),
img_size[1],3),dtype='uint8')))
img = Image.fromarray(img,'RGB')
imgdraw = ImageDraw.Draw(img)
imgdraw.text((0,img_size[0]),t,(255,255,255),
font=ImageFont.truetype('UbuntuMono-R.ttf',fontsize))
img = np.array(img, dtype='uint8')
row.append(img)
if (idx+1)%columns==0:
result.append(row)
row = []
result = np.array(result)
result = np.concatenate(result,axis=1)
result = np.concatenate(result,axis=1)
Image.fromarray(result).save(saveto) | [
"matplotlib.pyplot.title",
"numpy.abs",
"numpy.argmax",
"matplotlib.pyplot.bar",
"numpy.ones",
"numpy.argmin",
"numpy.argsort",
"torch.nn.NLLLoss",
"matplotlib.pyplot.figure",
"numpy.mean",
"skimage.transform.resize",
"numpy.exp",
"os.path.join",
"data.pixel_permutation",
"numpy.copy",
... | [((354, 375), 'matplotlib.use', 'matplotlib.use', (['"""Agg"""'], {}), "('Agg')\n", (368, 375), False, 'import matplotlib\n'), ((485, 508), 'numpy.argsort', 'np.argsort', (['PERMUTATION'], {}), '(PERMUTATION)\n', (495, 508), True, 'import numpy as np\n'), ((707, 719), 'torch.nn.NLLLoss', 'nn.NLLLoss', ([], {}), '()\n', (717, 719), False, 'from torch import nn\n'), ((1353, 1390), 'os.path.join', 'os.path.join', (['modeldir', '"""input_grads"""'], {}), "(modeldir, 'input_grads')\n", (1365, 1390), False, 'import os\n'), ((3338, 3363), 'progressbar.ProgressBar', 'progressbar.ProgressBar', ([], {}), '()\n', (3361, 3363), False, 'import progressbar\n'), ((4607, 4637), 'os.path.join', 'os.path.join', (['modeldir', '"""gifs"""'], {}), "(modeldir, 'gifs')\n", (4619, 4637), False, 'import os\n'), ((5871, 5886), 'numpy.squeeze', 'np.squeeze', (['img'], {}), '(img)\n', (5881, 5886), True, 'import numpy as np\n'), ((9071, 9087), 'numpy.array', 'np.array', (['result'], {}), '(result)\n', (9079, 9087), True, 'import numpy as np\n'), ((9101, 9131), 'numpy.concatenate', 'np.concatenate', (['result'], {'axis': '(1)'}), '(result, axis=1)\n', (9115, 9131), True, 'import numpy as np\n'), ((9144, 9174), 'numpy.concatenate', 'np.concatenate', (['result'], {'axis': '(1)'}), '(result, axis=1)\n', (9158, 9174), True, 'import numpy as np\n'), ((436, 460), 'data.pixel_permutation', 'data.pixel_permutation', ([], {}), '()\n', (458, 460), False, 'import data\n'), ((1037, 1073), 'os.path.join', 'os.path.join', (['modeldir', '"""checkpoint"""'], {}), "(modeldir, 'checkpoint')\n", (1049, 1073), False, 'import os\n'), ((1155, 1169), 'json.load', 'json.load', (['jsf'], {}), '(jsf)\n', (1164, 1169), False, 'import json\n'), ((1401, 1423), 'os.path.isdir', 'os.path.isdir', (['savedir'], {}), '(savedir)\n', (1414, 1423), False, 'import os\n'), ((1433, 1453), 'os.makedirs', 'os.makedirs', (['savedir'], {}), '(savedir)\n', (1444, 1453), False, 'import os\n'), ((1871, 1881), 'numpy.abs', 'np.abs', (['gx'], {}), '(gx)\n', (1877, 1881), True, 'import numpy as np\n'), ((2142, 2195), 'numpy.transpose', 'np.transpose', (['[0.8 * x + 0.2 * gx, gx, gx]', '[1, 2, 0]'], {}), '([0.8 * x + 0.2 * gx, gx, gx], [1, 2, 0])\n', (2154, 2195), True, 'import numpy as np\n'), ((4464, 4473), 'numpy.exp', 'np.exp', (['o'], {}), '(o)\n', (4470, 4473), True, 'import numpy as np\n'), ((4517, 4526), 'numpy.exp', 'np.exp', (['o'], {}), '(o)\n', (4523, 4526), True, 'import numpy as np\n'), ((4648, 4669), 'os.path.isdir', 'os.path.isdir', (['gifdir'], {}), '(gifdir)\n', (4661, 4669), False, 'import os\n'), ((4679, 4698), 'os.makedirs', 'os.makedirs', (['gifdir'], {}), '(gifdir)\n', (4690, 4698), False, 'import os\n'), ((5356, 5391), 'os.path.join', 'os.path.join', (['modeldir', '"""best.jpeg"""'], {}), "(modeldir, 'best.jpeg')\n", (5368, 5391), False, 'import os\n'), ((5660, 5696), 'os.path.join', 'os.path.join', (['modeldir', '"""worst.jpeg"""'], {}), "(modeldir, 'worst.jpeg')\n", (5672, 5696), False, 'import os\n'), ((6238, 6309), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'num': '(1)', 'figsize': '(4, 4)', 'dpi': '(70)', 'facecolor': '"""w"""', 'edgecolor': '"""k"""'}), "(num=1, figsize=(4, 4), dpi=70, facecolor='w', edgecolor='k')\n", (6248, 6309), True, 'import matplotlib.pyplot as plt\n'), ((6454, 6499), 'matplotlib.pyplot.bar', 'plt.bar', (['x_rest', 'y_rest'], {'width': '(0.8)', 'color': '"""r"""'}), "(x_rest, y_rest, width=0.8, color='r')\n", (6461, 6499), True, 'import matplotlib.pyplot as plt\n'), ((6509, 6556), 'matplotlib.pyplot.bar', 'plt.bar', (['x_label', 'y_label'], {'width': '(0.8)', 'color': '"""g"""'}), "(x_label, y_label, width=0.8, color='g')\n", (6516, 6556), True, 'import matplotlib.pyplot as plt\n'), ((6562, 6582), 'matplotlib.pyplot.title', 'plt.title', (['"""Outputs"""'], {}), "('Outputs')\n", (6571, 6582), True, 'import matplotlib.pyplot as plt\n'), ((6591, 6629), 'matplotlib.pyplot.rcParams.update', 'plt.rcParams.update', (["{'font.size': 10}"], {}), "({'font.size': 10})\n", (6610, 6629), True, 'import matplotlib.pyplot as plt\n'), ((6894, 6908), 'matplotlib.pyplot.close', 'plt.close', (['fig'], {}), '(fig)\n', (6903, 6908), True, 'import matplotlib.pyplot as plt\n'), ((8282, 8352), 'skimage.transform.resize', 'resize', (['img', '[280, 280]'], {'order': '(0)', 'preserve_range': '(True)', 'mode': '"""constant"""'}), "(img, [280, 280], order=0, preserve_range=True, mode='constant')\n", (8288, 8352), False, 'from skimage.transform import resize\n'), ((8362, 8396), 'numpy.array', 'np.array', (['(255 * img)'], {'dtype': '"""uint8"""'}), "(255 * img, dtype='uint8')\n", (8370, 8396), True, 'import numpy as np\n'), ((1088, 1125), 'os.path.join', 'os.path.join', (['modeldir', '"""params.json"""'], {}), "(modeldir, 'params.json')\n", (1100, 1125), False, 'import os\n'), ((1609, 1634), 'numpy.reshape', 'np.reshape', (['x', 'IMAGE_SIZE'], {}), '(x, IMAGE_SIZE)\n', (1619, 1634), True, 'import numpy as np\n'), ((1691, 1716), 'numpy.reshape', 'np.reshape', (['x', 'IMAGE_SIZE'], {}), '(x, IMAGE_SIZE)\n', (1701, 1716), True, 'import numpy as np\n'), ((1760, 1773), 'numpy.squeeze', 'np.squeeze', (['x'], {}), '(x)\n', (1770, 1773), True, 'import numpy as np\n'), ((1775, 1789), 'numpy.squeeze', 'np.squeeze', (['gx'], {}), '(gx)\n', (1785, 1789), True, 'import numpy as np\n'), ((3554, 3585), 'torch.autograd.Variable', 'Variable', (['x'], {'requires_grad': '(True)'}), '(x, requires_grad=True)\n', (3562, 3585), False, 'from torch.autograd import Variable\n'), ((3586, 3597), 'torch.autograd.Variable', 'Variable', (['y'], {}), '(y)\n', (3594, 3597), False, 'from torch.autograd import Variable\n'), ((3994, 4016), 'numpy.argmax', 'np.argmax', (['best_losses'], {}), '(best_losses)\n', (4003, 4016), True, 'import numpy as np\n'), ((4346, 4368), 'numpy.argmin', 'np.argmin', (['wrst_losses'], {}), '(wrst_losses)\n', (4355, 4368), True, 'import numpy as np\n'), ((5906, 5940), 'numpy.ones', 'np.ones', (['IMAGE_SIZE'], {'dtype': '"""uint8"""'}), "(IMAGE_SIZE, dtype='uint8')\n", (5913, 5940), True, 'import numpy as np\n'), ((7010, 7031), 'numpy.squeeze', 'np.squeeze', (['output[i]'], {}), '(output[i])\n', (7020, 7031), True, 'import numpy as np\n'), ((7032, 7049), 'numpy.squeeze', 'np.squeeze', (['label'], {}), '(label)\n', (7042, 7049), True, 'import numpy as np\n'), ((7225, 7266), 'numpy.repeat', 'np.repeat', (['i[:, :, np.newaxis]', '(3)'], {'axis': '(2)'}), '(i[:, :, np.newaxis], 3, axis=2)\n', (7234, 7266), True, 'import numpy as np\n'), ((7440, 7470), 'numpy.concatenate', 'np.concatenate', (['(i, p)'], {'axis': '(1)'}), '((i, p), axis=1)\n', (7454, 7470), True, 'import numpy as np\n'), ((8466, 8509), 'numpy.repeat', 'np.repeat', (['img[:, :, np.newaxis]', '(3)'], {'axis': '(2)'}), '(img[:, :, np.newaxis], 3, axis=2)\n', (8475, 8509), True, 'import numpy as np\n'), ((8698, 8725), 'PIL.Image.fromarray', 'Image.fromarray', (['img', '"""RGB"""'], {}), "(img, 'RGB')\n", (8713, 8725), False, 'from PIL import Image, ImageDraw, ImageFont\n'), ((8747, 8766), 'PIL.ImageDraw.Draw', 'ImageDraw.Draw', (['img'], {}), '(img)\n', (8761, 8766), False, 'from PIL import Image, ImageDraw, ImageFont\n'), ((8922, 8950), 'numpy.array', 'np.array', (['img'], {'dtype': '"""uint8"""'}), "(img, dtype='uint8')\n", (8930, 8950), True, 'import numpy as np\n'), ((9178, 9201), 'PIL.Image.fromarray', 'Image.fromarray', (['result'], {}), '(result)\n', (9193, 9201), False, 'from PIL import Image, ImageDraw, ImageFont\n'), ((1899, 1909), 'numpy.min', 'np.min', (['gx'], {}), '(gx)\n', (1905, 1909), True, 'import numpy as np\n'), ((2844, 2861), 'torch.max', 'torch.max', (['output'], {}), '(output)\n', (2853, 2861), False, 'import torch\n'), ((6068, 6088), 'numpy.copy', 'np.copy', (['img_gif[-1]'], {}), '(img_gif[-1])\n', (6075, 6088), True, 'import numpy as np\n'), ((6126, 6150), 'numpy.squeeze', 'np.squeeze', (['(255 * img[t])'], {}), '(255 * img[t])\n', (6136, 6150), True, 'import numpy as np\n'), ((1912, 1922), 'numpy.max', 'np.max', (['gx'], {}), '(gx)\n', (1918, 1922), True, 'import numpy as np\n'), ((1923, 1933), 'numpy.min', 'np.min', (['gx'], {}), '(gx)\n', (1929, 1933), True, 'import numpy as np\n'), ((8855, 8903), 'PIL.ImageFont.truetype', 'ImageFont.truetype', (['"""UbuntuMono-R.ttf"""', 'fontsize'], {}), "('UbuntuMono-R.ttf', fontsize)\n", (8873, 8903), False, 'from PIL import Image, ImageDraw, ImageFont\n'), ((1987, 1998), 'numpy.mean', 'np.mean', (['gx'], {}), '(gx)\n', (1994, 1998), True, 'import numpy as np\n'), ((1999, 2009), 'numpy.std', 'np.std', (['gx'], {}), '(gx)\n', (2005, 2009), True, 'import numpy as np\n'), ((2043, 2054), 'numpy.mean', 'np.mean', (['gx'], {}), '(gx)\n', (2050, 2054), True, 'import numpy as np\n'), ((2055, 2065), 'numpy.std', 'np.std', (['gx'], {}), '(gx)\n', (2061, 2065), True, 'import numpy as np\n')] |
#coding=utf-8
import cv2
import numpy as np
import mvsdk
import time
import threading
class Camera2:
def __init__(self):
DevList = mvsdk.CameraEnumerateDevice()
nDev = len(DevList)
if nDev < 1:
print("No camera was found!")
return
for i, DevInfo in enumerate(DevList):
print("{}: {} {}".format(i, DevInfo.GetFriendlyName(), DevInfo.GetPortType()))
DevInfo0 = DevList[0]
DevInfo1 = DevList[1]
# 打开相机
self.hCamera0 = 0
self.hCamera1 = 0
try:
self.hCamera0 = mvsdk.CameraInit(DevInfo0, -1, -1)
self.hCamera1 = mvsdk.CameraInit(DevInfo1, -1, -1)
print("init successfully", self.hCamera0, self.hCamera1)
except mvsdk.CameraException as e:
print("CameraInit Failed({}): {}".format(e.error_code, e.message) )
return
# 获取相机特性描述
self.cap0 = mvsdk.CameraGetCapability(self.hCamera0)
self.cap1 = mvsdk.CameraGetCapability(self.hCamera1)
# 判断是黑白相机还是彩色相机
monoCamera0 = (self.cap0.sIspCapacity.bMonoSensor != 0)
monoCamera1 = (self.cap1.sIspCapacity.bMonoSensor != 0)
# 黑白相机让ISP直接输出MONO数据,而不是扩展成R=G=B的24位灰度
if monoCamera0:
mvsdk.CameraSetIspOutFormat(self.hCamera0, mvsdk.CAMERA_MEDIA_TYPE_MONO8)
else:
mvsdk.CameraSetIspOutFormat(self.hCamera0, mvsdk.CAMERA_MEDIA_TYPE_BGR8)
if monoCamera1:
mvsdk.CameraSetIspOutFormat(self.hCamera1, mvsdk.CAMERA_MEDIA_TYPE_MONO8)
else:
mvsdk.CameraSetIspOutFormat(self.hCamera1, mvsdk.CAMERA_MEDIA_TYPE_BGR8)
# 相机模式切换成连续采集
mvsdk.CameraSetTriggerMode(self.hCamera0, 0)
mvsdk.CameraSetTriggerMode(self.hCamera1, 0)
# 手动曝光,曝光时间10ms
mvsdk.CameraSetAeState(self.hCamera0, 0)
mvsdk.CameraSetExposureTime(self.hCamera0, 10 * 1000)
mvsdk.CameraSetAnalogGain(self.hCamera0, 20)
mvsdk.CameraSetGain(self.hCamera0, 100, 131, 110)
mvsdk.CameraSetAeState(self.hCamera1, 0)
mvsdk.CameraSetExposureTime(self.hCamera1, 10 * 1000)
mvsdk.CameraSetAnalogGain(self.hCamera1, 20)
mvsdk.CameraSetGain(self.hCamera1, 100, 131, 110)
#mvsdk.CameraSetLutMode(self.hCamera, LUTMODE_PRESET);
# 让SDK内部取图线程开始工作
mvsdk.CameraPlay(self.hCamera0)
mvsdk.CameraPlay(self.hCamera1)
# 计算RGB buffer所需的大小,这里直接按照相机的最大分辨率来分配
self.FrameBufferSize0 = self.cap0.sResolutionRange.iWidthMax * self.cap0.sResolutionRange.iHeightMax * (1 if monoCamera0 else 3)
self.FrameBufferSize1 = self.cap1.sResolutionRange.iWidthMax * self.cap1.sResolutionRange.iHeightMax * (1 if monoCamera0 else 3)
# 分配RGB buffer,用来存放ISP输出的图像
# 备注:从相机传输到PC端的是RAW数据,在PC端通过软件ISP转为RGB数据(如果是黑白相机就不需要转换格式,但是ISP还有其它处理,所以也需要分配这个buffer)
self.pFrameBuffer0 = mvsdk.CameraAlignMalloc(self.FrameBufferSize0, 16)
self.pFrameBuffer1 = mvsdk.CameraAlignMalloc(self.FrameBufferSize1, 16)
self.state0 = False
self.state1 = False
self.frame0 = None
self.frame1 = None
print("init finish")
def read(self):
self.read_left()
self.read_right()
#t1 = threading.Thread(target=self.read_left)
#t2 = threading.Thread(target=self.read_right)
#t1.start()
#t2.start()
#t1.join()
#t2.join()
#print(self.state0, self.state1)
if self.state0 and self.state1:
return True, self.frame0, self.frame1
else:
return False, None, None
def read_left(self):
try:
pRawData, FrameHead = mvsdk.CameraGetImageBuffer(self.hCamera0, 200)
mvsdk.CameraImageProcess(self.hCamera0, pRawData, self.pFrameBuffer0, FrameHead)
mvsdk.CameraReleaseImageBuffer(self.hCamera0, pRawData)
# 此时图片已经存储在pFrameBuffer中,对于彩色相机pFrameBuffer=RGB数据,黑白相机pFrameBuffer=8位灰度数据
# 把pFrameBuffer转换成opencv的图像格式以进行后续算法处理
frame_data = (mvsdk.c_ubyte * FrameHead.uBytes).from_address(self.pFrameBuffer0)
frame = np.frombuffer(frame_data, dtype=np.uint8)
frame = frame.reshape((FrameHead.iHeight, FrameHead.iWidth, 1 if FrameHead.uiMediaType == mvsdk.CAMERA_MEDIA_TYPE_MONO8 else 3) )
frame = cv2.resize(frame, (640,480), interpolation = cv2.INTER_LINEAR)
self.frame0 = frame
self.state0 = True
except mvsdk.CameraException as e:
self.state0 = False
if e.error_code != mvsdk.CAMERA_STATUS_TIME_OUT:
print("CameraGetImageBuffer failed({}): {}".format(e.error_code, e.message) )
def read_right(self):
try:
pRawData, FrameHead = mvsdk.CameraGetImageBuffer(self.hCamera1, 200)
mvsdk.CameraImageProcess(self.hCamera1, pRawData, self.pFrameBuffer1, FrameHead)
mvsdk.CameraReleaseImageBuffer(self.hCamera1, pRawData)
# 此时图片已经存储在pFrameBuffer中,对于彩色相机pFrameBuffer=RGB数据,黑白相机pFrameBuffer=8位灰度数据
# 把pFrameBuffer转换成opencv的图像格式以进行后续算法处理
frame_data = (mvsdk.c_ubyte * FrameHead.uBytes).from_address(self.pFrameBuffer1)
frame = np.frombuffer(frame_data, dtype=np.uint8)
frame = frame.reshape((FrameHead.iHeight, FrameHead.iWidth, 1 if FrameHead.uiMediaType == mvsdk.CAMERA_MEDIA_TYPE_MONO8 else 3) )
frame = cv2.resize(frame, (640,480), interpolation = cv2.INTER_LINEAR)
self.frame1 = frame
self.state1 = True
except mvsdk.CameraException as e:
self.state1 = False
if e.error_code != mvsdk.CAMERA_STATUS_TIME_OUT:
print("CameraGetImageBuffer failed({}): {}".format(e.error_code, e.message) )
def __del__(self):
print("in __del__")
cv2.destroyAllWindows()
mvsdk.CameraUnInit(self.hCamera0)
mvsdk.CameraAlignFree(self.pFrameBuffer0)
mvsdk.CameraUnInit(self.hCamera1)
mvsdk.CameraAlignFree(self.pFrameBuffer1)
if __name__ == "__main__":
camera = Camera2()
state, frame0, frame1 = camera.read()
print(state)
while state and (cv2.waitKey(1) & 0xFF) != ord('q'):
begin = time.time()
state, frame0, frame1 = camera.read()
#cv2.imshow("Press q to end", frame0)
#cv2.imshow("frame2", frame1)
frame0 = frame0.copy()
frame1 = frame1.copy()
print("fps", 1/(time.time() - begin))
| [
"mvsdk.CameraSetGain",
"mvsdk.CameraSetTriggerMode",
"mvsdk.CameraUnInit",
"mvsdk.CameraGetCapability",
"mvsdk.CameraImageProcess",
"mvsdk.CameraSetIspOutFormat",
"cv2.destroyAllWindows",
"cv2.resize",
"cv2.waitKey",
"numpy.frombuffer",
"mvsdk.CameraGetImageBuffer",
"mvsdk.CameraInit",
"mvsd... | [((137, 166), 'mvsdk.CameraEnumerateDevice', 'mvsdk.CameraEnumerateDevice', ([], {}), '()\n', (164, 166), False, 'import mvsdk\n'), ((792, 832), 'mvsdk.CameraGetCapability', 'mvsdk.CameraGetCapability', (['self.hCamera0'], {}), '(self.hCamera0)\n', (817, 832), False, 'import mvsdk\n'), ((847, 887), 'mvsdk.CameraGetCapability', 'mvsdk.CameraGetCapability', (['self.hCamera1'], {}), '(self.hCamera1)\n', (872, 887), False, 'import mvsdk\n'), ((1439, 1483), 'mvsdk.CameraSetTriggerMode', 'mvsdk.CameraSetTriggerMode', (['self.hCamera0', '(0)'], {}), '(self.hCamera0, 0)\n', (1465, 1483), False, 'import mvsdk\n'), ((1486, 1530), 'mvsdk.CameraSetTriggerMode', 'mvsdk.CameraSetTriggerMode', (['self.hCamera1', '(0)'], {}), '(self.hCamera1, 0)\n', (1512, 1530), False, 'import mvsdk\n'), ((1551, 1591), 'mvsdk.CameraSetAeState', 'mvsdk.CameraSetAeState', (['self.hCamera0', '(0)'], {}), '(self.hCamera0, 0)\n', (1573, 1591), False, 'import mvsdk\n'), ((1594, 1647), 'mvsdk.CameraSetExposureTime', 'mvsdk.CameraSetExposureTime', (['self.hCamera0', '(10 * 1000)'], {}), '(self.hCamera0, 10 * 1000)\n', (1621, 1647), False, 'import mvsdk\n'), ((1650, 1694), 'mvsdk.CameraSetAnalogGain', 'mvsdk.CameraSetAnalogGain', (['self.hCamera0', '(20)'], {}), '(self.hCamera0, 20)\n', (1675, 1694), False, 'import mvsdk\n'), ((1697, 1746), 'mvsdk.CameraSetGain', 'mvsdk.CameraSetGain', (['self.hCamera0', '(100)', '(131)', '(110)'], {}), '(self.hCamera0, 100, 131, 110)\n', (1716, 1746), False, 'import mvsdk\n'), ((1750, 1790), 'mvsdk.CameraSetAeState', 'mvsdk.CameraSetAeState', (['self.hCamera1', '(0)'], {}), '(self.hCamera1, 0)\n', (1772, 1790), False, 'import mvsdk\n'), ((1793, 1846), 'mvsdk.CameraSetExposureTime', 'mvsdk.CameraSetExposureTime', (['self.hCamera1', '(10 * 1000)'], {}), '(self.hCamera1, 10 * 1000)\n', (1820, 1846), False, 'import mvsdk\n'), ((1849, 1893), 'mvsdk.CameraSetAnalogGain', 'mvsdk.CameraSetAnalogGain', (['self.hCamera1', '(20)'], {}), '(self.hCamera1, 20)\n', (1874, 1893), False, 'import mvsdk\n'), ((1896, 1945), 'mvsdk.CameraSetGain', 'mvsdk.CameraSetGain', (['self.hCamera1', '(100)', '(131)', '(110)'], {}), '(self.hCamera1, 100, 131, 110)\n', (1915, 1945), False, 'import mvsdk\n'), ((2024, 2055), 'mvsdk.CameraPlay', 'mvsdk.CameraPlay', (['self.hCamera0'], {}), '(self.hCamera0)\n', (2040, 2055), False, 'import mvsdk\n'), ((2058, 2089), 'mvsdk.CameraPlay', 'mvsdk.CameraPlay', (['self.hCamera1'], {}), '(self.hCamera1)\n', (2074, 2089), False, 'import mvsdk\n'), ((2533, 2583), 'mvsdk.CameraAlignMalloc', 'mvsdk.CameraAlignMalloc', (['self.FrameBufferSize0', '(16)'], {}), '(self.FrameBufferSize0, 16)\n', (2556, 2583), False, 'import mvsdk\n'), ((2607, 2657), 'mvsdk.CameraAlignMalloc', 'mvsdk.CameraAlignMalloc', (['self.FrameBufferSize1', '(16)'], {}), '(self.FrameBufferSize1, 16)\n', (2630, 2657), False, 'import mvsdk\n'), ((5084, 5107), 'cv2.destroyAllWindows', 'cv2.destroyAllWindows', ([], {}), '()\n', (5105, 5107), False, 'import cv2\n'), ((5110, 5143), 'mvsdk.CameraUnInit', 'mvsdk.CameraUnInit', (['self.hCamera0'], {}), '(self.hCamera0)\n', (5128, 5143), False, 'import mvsdk\n'), ((5146, 5187), 'mvsdk.CameraAlignFree', 'mvsdk.CameraAlignFree', (['self.pFrameBuffer0'], {}), '(self.pFrameBuffer0)\n', (5167, 5187), False, 'import mvsdk\n'), ((5190, 5223), 'mvsdk.CameraUnInit', 'mvsdk.CameraUnInit', (['self.hCamera1'], {}), '(self.hCamera1)\n', (5208, 5223), False, 'import mvsdk\n'), ((5226, 5267), 'mvsdk.CameraAlignFree', 'mvsdk.CameraAlignFree', (['self.pFrameBuffer1'], {}), '(self.pFrameBuffer1)\n', (5247, 5267), False, 'import mvsdk\n'), ((5436, 5447), 'time.time', 'time.time', ([], {}), '()\n', (5445, 5447), False, 'import time\n'), ((498, 532), 'mvsdk.CameraInit', 'mvsdk.CameraInit', (['DevInfo0', '(-1)', '(-1)'], {}), '(DevInfo0, -1, -1)\n', (514, 532), False, 'import mvsdk\n'), ((552, 586), 'mvsdk.CameraInit', 'mvsdk.CameraInit', (['DevInfo1', '(-1)', '(-1)'], {}), '(DevInfo1, -1, -1)\n', (568, 586), False, 'import mvsdk\n'), ((1084, 1157), 'mvsdk.CameraSetIspOutFormat', 'mvsdk.CameraSetIspOutFormat', (['self.hCamera0', 'mvsdk.CAMERA_MEDIA_TYPE_MONO8'], {}), '(self.hCamera0, mvsdk.CAMERA_MEDIA_TYPE_MONO8)\n', (1111, 1157), False, 'import mvsdk\n'), ((1169, 1241), 'mvsdk.CameraSetIspOutFormat', 'mvsdk.CameraSetIspOutFormat', (['self.hCamera0', 'mvsdk.CAMERA_MEDIA_TYPE_BGR8'], {}), '(self.hCamera0, mvsdk.CAMERA_MEDIA_TYPE_BGR8)\n', (1196, 1241), False, 'import mvsdk\n'), ((1263, 1336), 'mvsdk.CameraSetIspOutFormat', 'mvsdk.CameraSetIspOutFormat', (['self.hCamera1', 'mvsdk.CAMERA_MEDIA_TYPE_MONO8'], {}), '(self.hCamera1, mvsdk.CAMERA_MEDIA_TYPE_MONO8)\n', (1290, 1336), False, 'import mvsdk\n'), ((1348, 1420), 'mvsdk.CameraSetIspOutFormat', 'mvsdk.CameraSetIspOutFormat', (['self.hCamera1', 'mvsdk.CAMERA_MEDIA_TYPE_BGR8'], {}), '(self.hCamera1, mvsdk.CAMERA_MEDIA_TYPE_BGR8)\n', (1375, 1420), False, 'import mvsdk\n'), ((3185, 3231), 'mvsdk.CameraGetImageBuffer', 'mvsdk.CameraGetImageBuffer', (['self.hCamera0', '(200)'], {}), '(self.hCamera0, 200)\n', (3211, 3231), False, 'import mvsdk\n'), ((3235, 3320), 'mvsdk.CameraImageProcess', 'mvsdk.CameraImageProcess', (['self.hCamera0', 'pRawData', 'self.pFrameBuffer0', 'FrameHead'], {}), '(self.hCamera0, pRawData, self.pFrameBuffer0, FrameHead\n )\n', (3259, 3320), False, 'import mvsdk\n'), ((3319, 3374), 'mvsdk.CameraReleaseImageBuffer', 'mvsdk.CameraReleaseImageBuffer', (['self.hCamera0', 'pRawData'], {}), '(self.hCamera0, pRawData)\n', (3349, 3374), False, 'import mvsdk\n'), ((3593, 3634), 'numpy.frombuffer', 'np.frombuffer', (['frame_data'], {'dtype': 'np.uint8'}), '(frame_data, dtype=np.uint8)\n', (3606, 3634), True, 'import numpy as np\n'), ((3779, 3840), 'cv2.resize', 'cv2.resize', (['frame', '(640, 480)'], {'interpolation': 'cv2.INTER_LINEAR'}), '(frame, (640, 480), interpolation=cv2.INTER_LINEAR)\n', (3789, 3840), False, 'import cv2\n'), ((4144, 4190), 'mvsdk.CameraGetImageBuffer', 'mvsdk.CameraGetImageBuffer', (['self.hCamera1', '(200)'], {}), '(self.hCamera1, 200)\n', (4170, 4190), False, 'import mvsdk\n'), ((4194, 4279), 'mvsdk.CameraImageProcess', 'mvsdk.CameraImageProcess', (['self.hCamera1', 'pRawData', 'self.pFrameBuffer1', 'FrameHead'], {}), '(self.hCamera1, pRawData, self.pFrameBuffer1, FrameHead\n )\n', (4218, 4279), False, 'import mvsdk\n'), ((4278, 4333), 'mvsdk.CameraReleaseImageBuffer', 'mvsdk.CameraReleaseImageBuffer', (['self.hCamera1', 'pRawData'], {}), '(self.hCamera1, pRawData)\n', (4308, 4333), False, 'import mvsdk\n'), ((4548, 4589), 'numpy.frombuffer', 'np.frombuffer', (['frame_data'], {'dtype': 'np.uint8'}), '(frame_data, dtype=np.uint8)\n', (4561, 4589), True, 'import numpy as np\n'), ((4734, 4795), 'cv2.resize', 'cv2.resize', (['frame', '(640, 480)'], {'interpolation': 'cv2.INTER_LINEAR'}), '(frame, (640, 480), interpolation=cv2.INTER_LINEAR)\n', (4744, 4795), False, 'import cv2\n'), ((5390, 5404), 'cv2.waitKey', 'cv2.waitKey', (['(1)'], {}), '(1)\n', (5401, 5404), False, 'import cv2\n'), ((5628, 5639), 'time.time', 'time.time', ([], {}), '()\n', (5637, 5639), False, 'import time\n')] |
import numpy as np
import scipy.optimize as opt
import matplotlib.pyplot as plt
from scipy.integrate import quad
# Best-fit Planck values arXiv:1807.06209
#H0 = 67.66
#OM = 0.3111
#OL = 0.6889
#OK = 0
c = 299792.458
f = open("QSO_data.txt", "r")
l = f.readlines()
z = []
mu = []
sigma = []
for x in l:
z.append(float(x.split('\t')[0]))
mu.append(float(x.split('\t')[1]))
sigma.append(float(x.split('\t')[2]))
z = np.asarray(z)
mu = np.asarray(mu)
sigma = np.asarray(sigma)
Harray = np.linspace(60, 90, num=21)
OMarray = np.linspace(0, 1, num=21)
def chisqfunc_timesphere(h): # d_L = c/H0 (1+z) sin(ln(1+z))
a = h
dL = c/a * (1+z) * np.sin(np.log(1+z))
model = -5 + 5*np.log10(dL*1000000)
chisq = np.sum( ((mu - model)/sigma)**2 )
return chisq
def chisqfunc_rhct(h): # d_L = c/H0 (1+z) ln(1+z)
a = h
dL = c/a * (1+z) * np.log(1+z)
model = -5 + 5*np.log10(dL*1000000)
chisq = np.sum( ((mu - model)/sigma)**2 )
return chisq
def E_z(z, OM, OK, OL):
return 1/np.sqrt((1 + z)**3 * OM + (1 + z)**2 * OK + OL)
def chisqfunc_lcdm(arr):
H0 = arr[0]
Omega_m0 = arr[1]
Omega_l0 = arr[2]
Omega_k0 = 0
temp = []
for i in range(len(z)):
temp.append((1+z[i]) * (c/H0) * quad(E_z, 0, z[i], args=(Omega_m0, Omega_k0, Omega_l0))[0])
dL = np.asarray(temp)
model = -5 + 5*np.log10(dL*1000000)
chisq = np.sum( ((mu - model)/sigma)**2 )
return chisq
res_ts = []
res_rhct = []
res_lcdm = np.zeros((len(Harray), len(OMarray)))
for i in range(len(Harray)):
#res_ts.append(chisqfunc_timesphere(Harray[i]))
#res_rhct.append(chisqfunc_rhct(Harray[i]))
for j in range(len(OMarray)):
res_lcdm[i][j] = chisqfunc_lcdm((Harray[i], OMarray[j], 1-OMarray[j]))
res_ts = np.asarray(res_ts)
res_rhct = np.asarray(res_rhct)
#for h, cs_th, cs_rh in zip(Harray, res_ts, res_rhct):
#print("%f %f %f" % (h, cs_th, cs_rh))
(inda, indb) = np.unravel_index(res_lcdm.argmin(), res_lcdm.shape)
print(Harray[inda], OMarray[indb], res_lcdm[inda][indb])
#print(Harray[np.argmin(res_ts)], min(res_ts))
#print(Harray[np.argmin(res_rhct)], min(res_rhct))
'''
fig, ax = plt.subplots(1)
plt.errorbar(z, mu, yerr=sigma, fmt='o', zorder=0)
plt.plot(z, -5 + 5*np.log10( (c/Harray[np.argmin(res_ts)] * (1+z) * np.sin(np.log(1+z))) *1000000), label='Timesphere', zorder=5)
plt.plot(z, -5 + 5*np.log10( (c/Harray[np.argmin(res_rhct)] * (1+z) * np.log(1+z)) *1000000), label='RH=cT', zorder=10)
plt.show()
'''
| [
"numpy.sum",
"numpy.log",
"scipy.integrate.quad",
"numpy.asarray",
"numpy.linspace",
"numpy.log10",
"numpy.sqrt"
] | [((423, 436), 'numpy.asarray', 'np.asarray', (['z'], {}), '(z)\n', (433, 436), True, 'import numpy as np\n'), ((442, 456), 'numpy.asarray', 'np.asarray', (['mu'], {}), '(mu)\n', (452, 456), True, 'import numpy as np\n'), ((465, 482), 'numpy.asarray', 'np.asarray', (['sigma'], {}), '(sigma)\n', (475, 482), True, 'import numpy as np\n'), ((494, 521), 'numpy.linspace', 'np.linspace', (['(60)', '(90)'], {'num': '(21)'}), '(60, 90, num=21)\n', (505, 521), True, 'import numpy as np\n'), ((532, 557), 'numpy.linspace', 'np.linspace', (['(0)', '(1)'], {'num': '(21)'}), '(0, 1, num=21)\n', (543, 557), True, 'import numpy as np\n'), ((1693, 1711), 'numpy.asarray', 'np.asarray', (['res_ts'], {}), '(res_ts)\n', (1703, 1711), True, 'import numpy as np\n'), ((1723, 1743), 'numpy.asarray', 'np.asarray', (['res_rhct'], {}), '(res_rhct)\n', (1733, 1743), True, 'import numpy as np\n'), ((714, 749), 'numpy.sum', 'np.sum', (['(((mu - model) / sigma) ** 2)'], {}), '(((mu - model) / sigma) ** 2)\n', (720, 749), True, 'import numpy as np\n'), ((899, 934), 'numpy.sum', 'np.sum', (['(((mu - model) / sigma) ** 2)'], {}), '(((mu - model) / sigma) ** 2)\n', (905, 934), True, 'import numpy as np\n'), ((1264, 1280), 'numpy.asarray', 'np.asarray', (['temp'], {}), '(temp)\n', (1274, 1280), True, 'import numpy as np\n'), ((1328, 1363), 'numpy.sum', 'np.sum', (['(((mu - model) / sigma) ** 2)'], {}), '(((mu - model) / sigma) ** 2)\n', (1334, 1363), True, 'import numpy as np\n'), ((841, 854), 'numpy.log', 'np.log', (['(1 + z)'], {}), '(1 + z)\n', (847, 854), True, 'import numpy as np\n'), ((986, 1037), 'numpy.sqrt', 'np.sqrt', (['((1 + z) ** 3 * OM + (1 + z) ** 2 * OK + OL)'], {}), '((1 + z) ** 3 * OM + (1 + z) ** 2 * OK + OL)\n', (993, 1037), True, 'import numpy as np\n'), ((655, 668), 'numpy.log', 'np.log', (['(1 + z)'], {}), '(1 + z)\n', (661, 668), True, 'import numpy as np\n'), ((684, 706), 'numpy.log10', 'np.log10', (['(dL * 1000000)'], {}), '(dL * 1000000)\n', (692, 706), True, 'import numpy as np\n'), ((869, 891), 'numpy.log10', 'np.log10', (['(dL * 1000000)'], {}), '(dL * 1000000)\n', (877, 891), True, 'import numpy as np\n'), ((1298, 1320), 'numpy.log10', 'np.log10', (['(dL * 1000000)'], {}), '(dL * 1000000)\n', (1306, 1320), True, 'import numpy as np\n'), ((1198, 1253), 'scipy.integrate.quad', 'quad', (['E_z', '(0)', 'z[i]'], {'args': '(Omega_m0, Omega_k0, Omega_l0)'}), '(E_z, 0, z[i], args=(Omega_m0, Omega_k0, Omega_l0))\n', (1202, 1253), False, 'from scipy.integrate import quad\n')] |
from winning.normaldist import normcdf, normpdf
import numpy as np
import math
from collections import Counter
#########################################################################################
# Operations on univariate atomic distributions supported on evenly spaced points #
#########################################################################################
# A density is just a list of numbers interpreted as a density on the integers
# Where a density is to be interpreted on a lattice with some other unit, the unit parameter is supplied and
# this is equal to the spacing between lattice points. However, most operations are implemented on the
# lattice that is the natural numbers.
def integer_shift(cdf, k):
""" Shift cdf to the *right* so it represents the cdf for Y ~ X + k*unit
:param cdf:
:param k: int Number of lattice points
:return:
"""
if k < 0:
return np.append(cdf[abs(k):], cdf[-1] * np.ones(abs(k)))
elif k == 0:
return cdf
else:
return np.append(np.zeros(k), cdf[:-k])
def fractional_shift(cdf, x):
""" Shift cdf to the *right* so it represents the cdf for Y ~ X + x*unit
:param cdf:
:param x: float Number of lattice points to shift (need not be integer)
:return:
"""
(l, lc), (u, uc) = _low_high(x)
try:
return lc * integer_shift(cdf, l) + uc * integer_shift(cdf, u)
except:
raise Exception('nasty bug')
def _low_high(offset):
""" Represent a float offset as combination of two discrete ones """
l = math.floor(offset)
u = math.ceil(offset)
r = offset - l
return (l, 1 - r), (u, r)
def density_from_samples(x: [float], L: int, unit=1.0):
low_highs = [ _low_high(xi / unit) for xi in x]
density = [0 for _ in range(2 * L + 1)]
mass = 0
for lh in low_highs:
for (lc, wght) in lh:
rel_loc = min(2 * L, max(lc + L, 0))
mass += wght
density[rel_loc] += wght
total_mass = sum(density)
return [d / total_mass for d in density]
def fractional_shift_density(density, x):
""" Shift pdf to the *right* so it represents the pdf for Y ~ X + x*unit """
cdf = pdf_to_cdf(density)
shifted_cdf = fractional_shift(cdf, x)
return cdf_to_pdf(shifted_cdf)
def center_density(density):
""" Shift density to near its mean """
m = mean_of_density(density, unit=1.0)
return fractional_shift_density(density, -m)
### Interpretation of density on a grid with known spacing
def implied_L(density):
return int((len(density) - 1) / 2)
def mean_of_density(density, unit):
L = implied_L(density)
pts = symmetric_lattice(L=L, unit=unit)
return np.inner(density, pts)
def symmetric_lattice(L, unit):
assert isinstance(L, int), "Expecting L to be integer"
return unit * np.linspace(-L, L, 2 * L + 1)
def middle_of_density(density, L:int, do_padding=False):
"""
:param density:
:param L:
:return: density of len 2*L+1
"""
L0 = implied_L(density)
if (L0==L) or ((L0<L) and not do_padding):
return density
elif L0<L:
L0 = implied_L(density)
n_extra=L-L0
padding = [ 0 for _ in range(n_extra) ]
return padding + list(density) + padding
else:
n_extra = L0-L
cdf = cdf_to_pdf(density)
cdf_truncated = cdf[n_extra:-n_extra]
pdf_truncated = cdf_to_pdf(cdf_truncated)
return pdf_truncated
def convolve_two(density1, density2, L=None, do_padding=False):
"""
If X ~ density1 and Y ~ density2 are represented on symmetric lattices
then the returned density will approximate X+Y, albeit not perfectly if
the support of X or Y comes too close to the end of the lattice. Either way
the mean will be preserved.
:param density1: 2L+1
:param density2: Any odd length
:return:
Note that if, on the other hand, you wish to preserve densities exactly then you can simply
use np.convolve
"""
assert len(density1) % 2 ==1, 'Expecting odd length density1 '
assert len(density2) % 2 == 1, 'Expecting odd length density2 '
if L is None:
L = implied_L(density1)
mu1 = mean_of_density(density1, unit=1)
mu2 = mean_of_density(density2, unit=1)
density = np.convolve(density1, density2)
middle = middle_of_density(density=density, L=L, do_padding=do_padding)
mu = mean_of_density(middle, unit=1)
mu_diff = mu-(mu1+mu2)
pdf_shifted = fractional_shift_density(middle,-mu_diff)
if sum(pdf_shifted)<0.9:
raise ValueError('Convolution of two densities caused too much mass loss - increase L')
return pdf_shifted
def convolve_many(densities, L=None, do_padding=True):
"""
:param density[0] has length 2L+1
:return:
Note that if, on the other hand, you wish to preserve densities exactly then you can simply
use np.convolve
"""
for k,d in enumerate(densities):
assert len(d) % 2 ==1, 'Expecting odd length density['+str(k)+']'
mu_sum = sum( [ mean_of_density(density, unit=1) for density in densities ])
if L is None:
L = implied_L(densities[0])
full_density = [ p for p in densities[0] ]
for density in densities[1:-1]:
full_density = convolve_two(density1=full_density, density2=density, L=L, do_padding=False)
full_density = convolve_two(density1=full_density, density2=densities[-1], L=L, do_padding=do_padding)
mu = mean_of_density(full_density, unit=1)
mu_diff = mu-mu_sum
pdf_shifted = fractional_shift_density(full_density,-mu_diff)
return pdf_shifted
#############################################
# Simple family of skewed distributions #
#############################################
# As noted above, densities are simply vectors. So if these utility functions are used
# to create densities with unit=0.02, say, then the user must keep the unit chosen for
# later interpretation.
def skew_normal_density(L, unit, loc=0, scale=1.0, a=2.0):
""" Skew normal as a lattice density """
lattice = symmetric_lattice(L=L, unit=unit)
density = np.array([_unnormalized_skew_cdf(x, loc=loc, scale=scale, a=a) for x in lattice])
density = density / np.sum(density)
density = center_density(density)
density = fractional_shift(density, loc/unit )
return density
def _unnormalized_skew_cdf(x, loc=0, scale=1.0, a=2.0):
""" Proportional to skew-normal density
:param x:
:param loc: location
:param scale: scale
:param a: controls skew (a>0 means fat tail on right)
:return: np.array length 2*L+1
"""
t = (x - loc) / scale
return 2 / scale * normpdf(t) * normcdf(a * t)
def sample_from_cdf(cdf, n_samples, unit=1.0, add_noise=False):
""" Monte Carlo sample """
rvs = np.random.rand(n_samples)
performances = [unit * sum([rv > c for c in cdf]) for rv in rvs]
if add_noise:
noise = 0.00001 * unit * np.random.randn(n_samples)
return [s + x for s, x in zip(performances, noise)]
else:
return performances
def sample_from_cdf_with_noise(cdf, n_samples, unit=1.0):
return sample_from_cdf(cdf=cdf, n_samples=n_samples, unit=unit, add_noise=True)
#############################################
# Order statistics on lattices #
#############################################
# ------- Nothing below here depends on the unit chosen -------------
def pdf_to_cdf(density):
""" Prob( X <= k ) """
# If pdf's were created with unit in mind, this is really Prob( X<=k*unit )
return np.cumsum(density)
def cdf_to_pdf(cumulative):
""" Given cumulative distribution on lattice, return the pdf """
prepended = np.insert(cumulative, 0, 0.)
return np.diff(prepended)
def winner_of_many(densities, multiplicities=None):
""" The PDF of the minimum of the random variables represented by densities
:param densities: [ np.array ]
:return: np.array
"""
d = densities[0]
multiplicities = multiplicities or [None for _ in densities]
m = multiplicities[0]
for d2, m2 in zip(densities[1:], multiplicities[1:]):
d, m = _winner_of_two_pdf(d, d2, multiplicityA=m, multiplicityB=m2)
return d, m
def sample_winner_of_many(densities, nSamples=5000):
""" The PDF of the minimum of the integer random variables represented by densities, by Monte Carlo """
cdfs = [pdf_to_cdf(density) for density in densities]
cols = [sample_from_cdf(cdf, nSamples) for cdf in cdfs]
rows = map(list, zip(*cols))
D = [min(row) for row in rows]
density = np.bincount(D, minlength=len(densities[0])) / (1.0 * nSamples)
return density
def get_the_rest(density, densityAll, multiplicityAll, cdf=None, cdfAll=None):
""" Returns expected _conditional_payoff_against_rest broken down by score,
where _conditional_payoff_against_rest is 1 if we are better than rest (lower) and 1/(1+multiplicity) if we are equal
"""
# Use np.sum( expected_payoff ) for the expectation
if cdf is None:
cdf = pdf_to_cdf(density)
if cdfAll is None:
cdfAll = pdf_to_cdf(densityAll)
if density is None:
density = cdf_to_pdf(cdf)
if densityAll is None: # Why do we need this??
densityAll = cdf_to_pdf(cdfAll)
S = 1 - cdfAll
S1 = 1 - cdf
Srest = (S + 1e-18) / (S1 + 1e-6)
cdfRest = 1 - Srest
# Multiplicity inversion (uses notation from blog post)
# This is written up in my blog post and the paper
m = multiplicityAll
f1 = density
m1 = 1.0
fRest = cdf_to_pdf(cdfRest)
numer = m * f1 * Srest + m * (f1 + S1) * fRest - m1 * f1 * (Srest + fRest)
denom = fRest * (f1 + S1)
multiplicityLeftTail = (1e-18 + numer) / (1e-18 + denom)
multiplicityRest = multiplicityLeftTail
T1 = (S1 + 1.0e-18) / (
f1 + 1e-6) # This calculation is more stable on the right tail. It should tend to zero eventually
Trest = (Srest + 1e-18) / (fRest + 1e-6)
multiplicityRightTail = m * Trest / (1 + T1) + m - m1 * (1 + Trest) / (1 + T1)
k = list(f1 == max(f1)).index(True)
multiplicityRest[k:] = multiplicityRightTail[k:]
return cdfRest, multiplicityRest
def expected_payoff(density, densityAll, multiplicityAll, cdf=None, cdfAll=None):
cdfRest, multiplicityRest = get_the_rest(density=density, densityAll=densityAll, multiplicityAll=multiplicityAll, cdf=cdf, cdfAll=cdfAll)
return _conditional_payoff_against_rest(density=density, densityRest=None, multiplicityRest=multiplicityRest, cdf=cdf, cdfRest=cdfRest)
def _winner_of_two_pdf(densityA, densityB, multiplicityA=None, multiplicityB=None, cdfA=None, cdfB=None):
""" The PDF of the minimum of two random variables represented by densities
:param densityA: np.array
:param densityB: np.array
:return: density, multiplicity
"""
if cdfA is None:
cdfA = pdf_to_cdf(densityA)
if cdfB is None:
cdfB = pdf_to_cdf(densityB)
cdfMin = 1 - np.multiply(1 - cdfA, 1 - cdfB)
density = cdf_to_pdf(cdfMin)
L = implied_L(density)
if multiplicityA is None:
multiplicityA = np.ones(2 * L + 1)
if multiplicityB is None:
multiplicityB = np.ones(2 * L + 1)
winA, draw, winB = _conditional_win_draw_loss(densityA, densityB, cdfA, cdfB)
try:
multiplicity = (winA * multiplicityA + draw * (multiplicityA + multiplicityB) + winB * multiplicityB + 1e-18) / (
winA + draw + winB + 1e-18)
except ValueError:
raise Exception('hit nasty bug')
pass
return density, multiplicity
def _loser_of_two_pdf(densityA, densityB):
reverse_density, reverse_multiplicity = _winner_of_two_pdf(np.flip(densityA), np.flip(densityB))
return np.flip(reverse_density), np.flip(reverse_multiplicity)
def beats(densityA, multiplicityA, densityB, multiplicityB):
"""
Returns expected _conditional_payoff_against_rest broken down by score
"""
# use np.sum( _conditional_payoff_against_rest) for the expectation
cdfA = pdf_to_cdf(densityA)
cdfB = pdf_to_cdf(densityB)
win, draw, loss = _conditional_win_draw_loss(densityA, densityB, cdfA, cdfB)
return sum( win + draw * (1+multiplicityA) / (2 + multiplicityB + multiplicityA ) )
def state_prices_from_densities(densities:[[float]], densityAll=None, multiplicityAll=None)->[float]:
"""
:param densities: List of performance distributions
:return: state prices
"""
if (densityAll is None) or (multiplicityAll is None):
densityAll, multiplicityAll = winner_of_many(densities, multiplicities=None)
cdfAll = pdf_to_cdf(densityAll)
prices = list()
for k, density in enumerate(densities):
cdfRest, multiplicityRest = get_the_rest(density=density, densityAll=None,
multiplicityAll=multiplicityAll, cdf=None,
cdfAll=cdfAll)
pdfRest = cdf_to_pdf(cdfRest)
multiplicity = np.array([1.0 for _ in density])
price_k = beats(densityA=density, multiplicityA=multiplicity, densityB=pdfRest, multiplicityB=multiplicityRest)
prices.append(price_k)
sum_p = sum(prices)
return [pi / sum_p for pi in prices]
def symmetric_state_prices_from_densities(densities:[[float]], densityAll=None, multiplicityAll=None, with_all=False)->[[float]]:
if (densityAll is None) or (multiplicityAll is None):
densityAll, multiplicityAll = winner_of_many(densities, multiplicities=None)
n = len(densities)
bi = np.ndarray(shape=(n, n))
for h0 in range(n):
density0 = densities[h0]
cdfRest0, multiplicityRest0 = get_the_rest(density=density0, densityAll=densityAll,
multiplicityAll=multiplicityAll, cdf=None, cdfAll=None)
for h1 in range(n):
if h1 > h0:
density1 = densities[h1]
cdfRest01, multiplicityRest01 = get_the_rest(density=density1, densityAll=None,
multiplicityAll=multiplicityRest0, cdf=None,
cdfAll=cdfRest0)
pdfRest01 = cdf_to_pdf(cdfRest01)
loser01, loser_multiplicity01 = _loser_of_two_pdf(density0, density1)
bi[h0, h1] = beats(loser01, loser_multiplicity01, pdfRest01, multiplicityRest01)
bi[h1, h0] = bi[h0, h1]
if with_all:
return bi, densityAll, multiplicityAll
else:
return bi
def two_prices_from_densities(densities:[[float]], densityAll=None, multiplicityAll=None, with_all=False)->[[float]]:
q, densityAll, multiplicityAll = symmetric_state_prices_from_densities(densities=densities, densityAll=densityAll, multiplicityAll=multiplicityAll, with_all=True)
w = state_prices_from_densities(densities=densities, densityAll=densityAll, multiplicityAll=multiplicityAll)
pl = [0 for _ in w]
n = len(w)
for i in range(n):
for j in range(i+1,n):
pl[i] += q[i,j]
pl[j] += q[i,j]
sum_pl = sum(pl)
pl = [ 2.0*pli/sum_pl for pli in pl]
assert abs(sum(pl)-2.0)<0.01
s = [ bi-wi for bi, wi in zip(pl,w)]
if with_all:
return w, s, densityAll, multiplicityAll
else:
return w , s
def five_prices_from_five_densities(densities:[[float]])->[[float]]:
"""
Rank probabilities for five independent contestants
returns [ [first probs], ..., [fifth probs] ]
"""
assert(len(densities)==5)
rdensities = [ np.asarray([ p for p in reversed(d)]) for d in densities ]
w1, w2 = two_prices_from_densities(densities=densities, with_all=False)
w5, w4 = two_prices_from_densities(densities=rdensities, with_all=False)
w3 = [1.0-w1i-w2i-w4i-w5i for w1i,w2i,w4i,w5i in zip(w1,w2,w4,w5) ]
return [ w1, w2, w3, w4, w5 ]
def densities_from_events(scores:[int], events:[[float]], L:int, unit:float):
"""
:param scores: List of current scores
:param events: List of densities of future events
:param L:
:param unit:
:return:
"""
assert len(scores)==len(events)
low_score = min(scores)
adjusted_scores = [ s-low_score for s in scores ]
if True:
for k,adj_score in enumerate(adjusted_scores):
adapted_L = int(math.ceil(abs(adj_score/unit)))
events[k].append( density_from_samples(x=[adj_score],L=adapted_L, unit=unit) )
densities = [ convolve_many( densities=event, L=L ) for event in events ]
return densities
def state_prices_from_events(scores:[int], events:[[float]], L:int, unit:float):
densities = densities_from_events(scores=scores, events=events, L=L, unit=unit )
return state_prices_from_densities(densities)
def _conditional_win_draw_loss(densityA, densityB, cdfA, cdfB):
""" Conditional win, draw and loss probability lattices for a two ratings race """
win = densityA * (1 - cdfB)
draw = densityA * densityB
lose = densityB * (1 - cdfA)
return win, draw, lose
def _conditional_payoff_against_rest(density, densityRest, multiplicityRest, cdf=None, cdfRest=None):
""" Returns expected _conditional_payoff_against_rest broken down by score, where _conditional_payoff_against_rest is 1 if we are better than rest (lower) and 1/(1+multiplicity) if we are equal """
# use np.sum( _conditional_payoff_against_rest) for the expectation
if cdf is None:
cdf = pdf_to_cdf(density)
if cdfRest is None:
cdfRest = pdf_to_cdf(densityRest)
if density is None:
density = cdf_to_pdf(cdf)
if densityRest is None:
densityRest = cdf_to_pdf(cdfRest)
win, draw, loss = _conditional_win_draw_loss(density, densityRest, cdf, cdfRest)
return win + draw / (1 + multiplicityRest)
def densities_and_coefs_from_offsets(density, offsets):
""" Given a density and a list of offsets (which might be non-integer) this
returns a list of translated densities
:param density: np.ndarray
:param offsets: [ float ]
:return: [ np.ndarray ]
"""
cdf = pdf_to_cdf(density)
coefs = [_low_high(offset) for offset in offsets]
cdfs = [lc * integer_shift(cdf, l) + uc * integer_shift(cdf, u) for (l, lc), (u, uc) in coefs]
pdfs = [cdf_to_pdf(cdf) for cdf in cdfs]
return pdfs, coefs
def densities_from_offsets(density, offsets):
return densities_and_coefs_from_offsets(density, offsets)[0]
def state_prices_from_offsets(density, offsets):
""" Returns a list of state prices for a race where all horses have the same density
up to a translation (the offsets)
"""
# See the paper for a definition of state price
# Be aware that this may fail if offsets provided are integers rather than float
densities = densities_from_offsets(density, offsets)
densityAll, multiplicityAll = winner_of_many(densities)
return implicit_state_prices(density, densityAll=densityAll, multiplicityAll=multiplicityAll, offsets=offsets)
def implicit_state_prices(density, densityAll, multiplicityAll=None, cdf=None, cdfAll=None, offsets=None):
""" Returns the expected _conditional_payoff_against_rest as a function of location changes in cdf """
L = implied_L(density)
if cdf is None:
cdf = pdf_to_cdf(density)
if cdfAll is None:
cdfAll = pdf_to_cdf(densityAll)
if multiplicityAll is None:
multiplicityAll = np.ones(2 * L + 1)
if offsets is None:
offsets = range(int(-L / 2), int(L / 2))
implicit = list()
for k in offsets:
if k == int(k):
offset_cdf = integer_shift(cdf, k)
ip = expected_payoff(density=None, densityAll=densityAll, multiplicityAll=multiplicityAll, cdf=offset_cdf,
cdfAll=cdfAll)
implicit.append(np.sum(ip))
else:
(l, l_coef), (r, r_coef) = _low_high(k)
offset_cdf_left = integer_shift(cdf, l)
offset_cdf_right = integer_shift(cdf, r)
ip_left = expected_payoff(density=None, densityAll=densityAll, multiplicityAll=multiplicityAll,
cdf=offset_cdf_left, cdfAll=cdfAll)
ip_right = expected_payoff(density=None, densityAll=densityAll, multiplicityAll=multiplicityAll,
cdf=offset_cdf_right, cdfAll=cdfAll)
implicit.append(l_coef * np.sum(ip_left) + r_coef * np.sum(ip_right))
return implicit
| [
"numpy.sum",
"numpy.ones",
"numpy.inner",
"numpy.convolve",
"numpy.ndarray",
"numpy.multiply",
"numpy.random.randn",
"numpy.insert",
"numpy.cumsum",
"numpy.linspace",
"math.ceil",
"numpy.flip",
"math.floor",
"numpy.zeros",
"winning.normaldist.normpdf",
"numpy.diff",
"numpy.array",
... | [((1583, 1601), 'math.floor', 'math.floor', (['offset'], {}), '(offset)\n', (1593, 1601), False, 'import math\n'), ((1610, 1627), 'math.ceil', 'math.ceil', (['offset'], {}), '(offset)\n', (1619, 1627), False, 'import math\n'), ((2728, 2750), 'numpy.inner', 'np.inner', (['density', 'pts'], {}), '(density, pts)\n', (2736, 2750), True, 'import numpy as np\n'), ((4331, 4362), 'numpy.convolve', 'np.convolve', (['density1', 'density2'], {}), '(density1, density2)\n', (4342, 4362), True, 'import numpy as np\n'), ((6854, 6879), 'numpy.random.rand', 'np.random.rand', (['n_samples'], {}), '(n_samples)\n', (6868, 6879), True, 'import numpy as np\n'), ((7631, 7649), 'numpy.cumsum', 'np.cumsum', (['density'], {}), '(density)\n', (7640, 7649), True, 'import numpy as np\n'), ((7765, 7794), 'numpy.insert', 'np.insert', (['cumulative', '(0)', '(0.0)'], {}), '(cumulative, 0, 0.0)\n', (7774, 7794), True, 'import numpy as np\n'), ((7805, 7823), 'numpy.diff', 'np.diff', (['prepended'], {}), '(prepended)\n', (7812, 7823), True, 'import numpy as np\n'), ((13651, 13675), 'numpy.ndarray', 'np.ndarray', ([], {'shape': '(n, n)'}), '(shape=(n, n))\n', (13661, 13675), True, 'import numpy as np\n'), ((2862, 2891), 'numpy.linspace', 'np.linspace', (['(-L)', 'L', '(2 * L + 1)'], {}), '(-L, L, 2 * L + 1)\n', (2873, 2891), True, 'import numpy as np\n'), ((6270, 6285), 'numpy.sum', 'np.sum', (['density'], {}), '(density)\n', (6276, 6285), True, 'import numpy as np\n'), ((6732, 6746), 'winning.normaldist.normcdf', 'normcdf', (['(a * t)'], {}), '(a * t)\n', (6739, 6746), False, 'from winning.normaldist import normcdf, normpdf\n'), ((11063, 11094), 'numpy.multiply', 'np.multiply', (['(1 - cdfA)', '(1 - cdfB)'], {}), '(1 - cdfA, 1 - cdfB)\n', (11074, 11094), True, 'import numpy as np\n'), ((11209, 11227), 'numpy.ones', 'np.ones', (['(2 * L + 1)'], {}), '(2 * L + 1)\n', (11216, 11227), True, 'import numpy as np\n'), ((11282, 11300), 'numpy.ones', 'np.ones', (['(2 * L + 1)'], {}), '(2 * L + 1)\n', (11289, 11300), True, 'import numpy as np\n'), ((11777, 11794), 'numpy.flip', 'np.flip', (['densityA'], {}), '(densityA)\n', (11784, 11794), True, 'import numpy as np\n'), ((11796, 11813), 'numpy.flip', 'np.flip', (['densityB'], {}), '(densityB)\n', (11803, 11813), True, 'import numpy as np\n'), ((11826, 11850), 'numpy.flip', 'np.flip', (['reverse_density'], {}), '(reverse_density)\n', (11833, 11850), True, 'import numpy as np\n'), ((11852, 11881), 'numpy.flip', 'np.flip', (['reverse_multiplicity'], {}), '(reverse_multiplicity)\n', (11859, 11881), True, 'import numpy as np\n'), ((13095, 13129), 'numpy.array', 'np.array', (['[(1.0) for _ in density]'], {}), '([(1.0) for _ in density])\n', (13103, 13129), True, 'import numpy as np\n'), ((19574, 19592), 'numpy.ones', 'np.ones', (['(2 * L + 1)'], {}), '(2 * L + 1)\n', (19581, 19592), True, 'import numpy as np\n'), ((6719, 6729), 'winning.normaldist.normpdf', 'normpdf', (['t'], {}), '(t)\n', (6726, 6729), False, 'from winning.normaldist import normcdf, normpdf\n'), ((7000, 7026), 'numpy.random.randn', 'np.random.randn', (['n_samples'], {}), '(n_samples)\n', (7015, 7026), True, 'import numpy as np\n'), ((1060, 1071), 'numpy.zeros', 'np.zeros', (['k'], {}), '(k)\n', (1068, 1071), True, 'import numpy as np\n'), ((19976, 19986), 'numpy.sum', 'np.sum', (['ip'], {}), '(ip)\n', (19982, 19986), True, 'import numpy as np\n'), ((20563, 20578), 'numpy.sum', 'np.sum', (['ip_left'], {}), '(ip_left)\n', (20569, 20578), True, 'import numpy as np\n'), ((20590, 20606), 'numpy.sum', 'np.sum', (['ip_right'], {}), '(ip_right)\n', (20596, 20606), True, 'import numpy as np\n')] |
"""
The :mod:`Chapter01.my_neuron` module contains the :class:`MyNeuron` class.
The :class:`MyNeuron` class will be the building blocks for the neural network layers I want to create.
"""
# ==============================================================================
# Imported Modules
# ==============================================================================
from numpy import dot
from numpy.random import uniform
# ==============================================================================
# Class Definition
# ==============================================================================
class MyNeuron:
"""
:class:`MyNeuron` is a digital model of a neuron.
"""
def __init__(self, number_of_inputs, activation_function):
"""
Create a new instance of :class:`MyNeuron`.
Parameters
----------
number_of_inputs : int
The input vector size or number of input values.
activation_function : function
The activation function that will define this neuron.
"""
# Properties
self._high_weight_bias = 1.
self._low_weight_bias = -1.
self._activation_function = activation_function
# Attributes
self.weight = uniform(
size = number_of_inputs,
low = self.low_weight_bias,
high = self.high_weight_bias
)
"""
ndarray[float]: The weight value for each input.
The weights :math:`\left( w \\right)` will be a sequence :math:`\left(w_i\\right)_{i=1}^{n}`.
In this sequence, :math:`w_i` can be any value such that
.. math::
-1.0 \leq w_i \leq 1.0
"""
self.bias = uniform(
size = 1,
low = self.low_weight_bias,
high = self.high_weight_bias
)
"""
float: The bias value to add to the weighted sum.
The bias :math:`\left( b \\right)` can be any value such that
.. math::
-1.0 \leq b \leq 1.0
"""
@property
def high_weight_bias(self):
"""
float: The highest value a weight or bias value can take.
By default, this will be :math:`1.0`.
"""
return self._high_weight_bias
@property
def low_weight_bias(self):
"""
float: The lowest value a weight or bias value can take.
By default, this will be :math:`-1.0`.
"""
return self._low_weight_bias
@property
def activation_function(self):
"""
function: The activation function for this neuron.
This will be set when :class:`MyNeuron` is instantiated.
"""
return self._activation_function
def forward(self, x):
z = dot(x, self.weight) + self.bias
return self.activation_function(z)
| [
"numpy.dot",
"numpy.random.uniform"
] | [((1266, 1355), 'numpy.random.uniform', 'uniform', ([], {'size': 'number_of_inputs', 'low': 'self.low_weight_bias', 'high': 'self.high_weight_bias'}), '(size=number_of_inputs, low=self.low_weight_bias, high=self.\n high_weight_bias)\n', (1273, 1355), False, 'from numpy.random import uniform\n'), ((1754, 1823), 'numpy.random.uniform', 'uniform', ([], {'size': '(1)', 'low': 'self.low_weight_bias', 'high': 'self.high_weight_bias'}), '(size=1, low=self.low_weight_bias, high=self.high_weight_bias)\n', (1761, 1823), False, 'from numpy.random import uniform\n'), ((2830, 2849), 'numpy.dot', 'dot', (['x', 'self.weight'], {}), '(x, self.weight)\n', (2833, 2849), False, 'from numpy import dot\n')] |
import numpy as np
import pandas as pd
from scipy.sparse import issparse
from .scatters import scatters
from .utils import (
quiver_autoscaler,
default_quiver_args,
save_fig,
set_arrow_alpha,
set_stream_line_alpha,
)
from ..tools.dimension_reduction import reduceDimension
from ..tools.cell_vectors import cell_velocities
from ..tools.Markov import prepare_velocity_grid_data, velocity_on_grid, grid_velocity_filter
from ..tools.topography import VectorField
from ..tools.utils import update_dict
from ..tools.utils_vecCalc import vecfld_from_adata
from .scatters import docstrings
docstrings.delete_params("scatters.parameters", "show_legend", "kwargs", "save_kwargs")
import scipy as sc
# from licpy.lic import runlic
# moran'I on the velocity genes, etc.
# cellranger data, velocyto, comparison and phase diagram
def cell_wise_vectors_3d():
pass
def grid_vectors_3d():
pass
# def velocity(adata, type) # type can be either one of the three, cellwise, velocity on grid, streamline plot.
# """
#
# """
#
def plot_LIC_gray(tex):
"""GET_P estimates the posterior probability and part of the energy.
Arguments
---------
Y: 'np.ndarray'
Original data.
V: 'np.ndarray'
Original data.
sigma2: 'float'
sigma2 is defined as sum(sum((Y - V)**2)) / (N * D)
gamma: 'float'
Percentage of inliers in the samples. This is an inital value for EM iteration, and it is not important.
a: 'float'
Paramerter of the model of outliers. We assume the outliers obey uniform distribution, and the volume of outlier's variation space is a.
Returns
-------
P: 'np.ndarray'
Posterior probability, related to equation 27.
E: `np.ndarray'
Energy, related to equation 26.
"""
import matplotlib.pyplot as plt
tex = tex[:, ::-1]
tex = tex.T
M, N = tex.shape
texture = np.empty((M, N, 4), np.float32)
texture[:, :, 0] = tex
texture[:, :, 1] = tex
texture[:, :, 2] = tex
texture[:, :, 3] = 1
# texture = scipy.ndimage.rotate(texture,-90)
plt.figure()
plt.imshow(texture)
def line_integral_conv(
adata,
basis="umap",
U_grid=None,
V_grid=None,
xy_grid_nums=[50, 50],
method="yt",
cmap="viridis",
normalize=False,
density=1,
lim=(0, 1),
const_alpha=False,
kernellen=100,
V_threshold=None,
vector='velocity',
file=None,
save_show_or_return='show',
save_kwargs={},
g_kwargs_dict={},
):
"""Visualize vector field with quiver, streamline and line integral convolution (LIC), using velocity estimates on a grid from the associated data.
A white noise background will be used for texture as default. Adjust the bounds of lim in the range of [0, 1] which applies
upper and lower bounds to the values of line integral convolution and enhance the visibility of plots. When const_alpha=False,
alpha will be weighted spatially by the values of line integral convolution; otherwise a constant value of the given alpha is used.
Arguments
---------
adata: :class:`~anndata.AnnData`
AnnData object that contains U_grid and V_grid data
basis: `str` (default: trimap)
The dimension reduction method to use.
U_grid: 'np.ndarray' (default: None)
Original velocity on the first dimension of a 2 d grid.
V_grid: 'np.ndarray' (default: None)
Original velocity on the second dimension of a 2 d grid.
xy_grid_nums: `tuple` (default: (50, 50))
the number of grids in either x or y axis. The number of grids has to be the same on both dimensions.
method: 'float'
sigma2 is defined as sum(sum((Y - V)**2)) / (N * D)
cmap: 'float'
Percentage of inliers in the samples. This is an inital value for EM iteration, and it is not important.
normalize: 'float'
Paramerter of the model of outliers. We assume the outliers obey uniform distribution, and the volume of outlier's variation space is a.
density: 'float'
Paramerter of the model of outliers. We assume the outliers obey uniform distribution, and the volume of outlier's variation space is a.
lim: 'float'
Paramerter of the model of outliers. We assume the outliers obey uniform distribution, and the volume of outlier's variation space is a.
const_alpha: 'float'
Paramerter of the model of outliers. We assume the outliers obey uniform distribution, and the volume of outlier's variation space is a.
kernellen: 'float'
Paramerter of the model of outliers. We assume the outliers obey uniform distribution, and the volume of outlier's variation space is a.
V_threshold: `float` or `None` (default: None)
The threshold of velocity value for visualization
vector: `str` (default: `velocity`)
Which vector type will be used for plotting, one of {'velocity', 'acceleration'} or either velocity field or
acceleration field will be plotted.
save_show_or_return: {'show', 'save', 'return'} (default: `show`)
Whether to save, show or return the figure.
save_kwargs: `dict` (default: `{}`)
A dictionary that will passed to the save_fig function. By default it is an empty dictionary and the save_fig function
will use the {"path": None, "prefix": 'line_integral_conv', "dpi": None, "ext": 'pdf', "transparent": True, "close":
True, "verbose": True} as its parameters. Otherwise you can provide a dictionary that properly modify those keys
according to your needs.
Returns
-------
Nothing, but plot the vector field with quiver, streamline and line integral convolution (LIC).
"""
import matplotlib.pyplot as plt
X = adata.obsm["X_" + basis][:, :2] if "X_" + basis in adata.obsm.keys() else None
V = (
adata.obsm[vector + '_' + basis][:, :2]
if vector + '_' + basis in adata.obsm.keys()
else None
)
if X is None:
raise Exception(
f"The {basis} dimension reduction is not performed over your data yet."
)
if V is None:
raise Exception(
f"The {basis}_velocity velocity (or velocity) result does not existed in your data."
)
if U_grid is None or V_grid is None:
if "VecFld_" + basis in adata.uns.keys():
# first check whether the sparseVFC reconstructed vector field exists
X_grid_, V_grid = (
adata.uns["VecFld_" + basis]["VecFld"]["grid"],
adata.uns["VecFld_" + basis]["VecFld"]["grid_V"],
)
N = int(np.sqrt(V_grid.shape[0]))
U_grid = np.reshape(V_grid[:, 0], (N, N)).T
V_grid = np.reshape(V_grid[:, 1], (N, N)).T
elif "grid_velocity_" + basis in adata.uns.keys():
# then check whether the Gaussian Kernel vector field exists
X_grid_, V_grid_, _ = (
adata.uns["grid_velocity_" + basis]["X_grid"],
adata.uns["grid_velocity_" + basis]["V_grid"],
adata.uns["grid_velocity_" + basis]["D"],
)
U_grid = V_grid_[0, :, :].T
V_grid = V_grid_[1, :, :].T
else:
# if no VF or Gaussian Kernel vector fields, recreate it
grid_kwargs_dict = {
"density": None,
"smooth": None,
"n_neighbors": None,
"min_mass": None,
"autoscale": False,
"adjust_for_stream": True,
"V_threshold": None,
}
grid_kwargs_dict.update(g_kwargs_dict)
X_grid_, V_grid_, _ = velocity_on_grid(
X[:, [0, 1]], V[:, [0, 1]], xy_grid_nums, **grid_kwargs_dict
)
U_grid = V_grid_[0, :, :].T
V_grid = V_grid_[1, :, :].T
if V_threshold is not None:
mass = np.sqrt((V_grid ** 2).sum(0))
if V_threshold is not None:
V_grid[0][mass.reshape(V_grid[0].shape) < V_threshold] = np.nan
if method == "yt":
try:
import yt
except ImportError:
print(
"Please first install yt package to use the line integral convolution plot method. "
"Install instruction is provided here: https://yt-project.org/"
)
velocity_x_ori, velocity_y_ori, velocity_z_ori = (
U_grid,
V_grid,
np.zeros(U_grid.shape),
)
velocity_x = np.repeat(
velocity_x_ori[:, :, np.newaxis], V_grid.shape[1], axis=2
)
velocity_y = np.repeat(
velocity_y_ori[:, :, np.newaxis], V_grid.shape[1], axis=2
)
velocity_z = np.repeat(
velocity_z_ori[np.newaxis, :, :], V_grid.shape[1], axis=0
)
data = {}
data["velocity_x"] = (velocity_x, "km/s")
data["velocity_y"] = (velocity_y, "km/s")
data["velocity_z"] = (velocity_z, "km/s")
data["velocity_sum"] = (np.sqrt(velocity_x ** 2 + velocity_y ** 2), "km/s")
ds = yt.load_uniform_grid(
data, data["velocity_x"][0].shape, length_unit=(1.0, "Mpc")
)
slc = yt.SlicePlot(ds, "z", ["velocity_sum"])
slc.set_cmap("velocity_sum", cmap)
slc.set_log("velocity_sum", False)
slc.annotate_velocity(normalize=normalize)
slc.annotate_streamlines("velocity_x", "velocity_y", density=density)
slc.annotate_line_integral_convolution(
"velocity_x",
"velocity_y",
lim=lim,
const_alpha=const_alpha,
kernellen=kernellen,
)
slc.set_xlabel(basis + "_1")
slc.set_ylabel(basis + "_2")
slc.show()
if file is not None:
# plt.rc('font', family='serif', serif='Times')
# plt.rc('text', usetex=True)
# plt.rc('xtick', labelsize=8)
# plt.rc('ytick', labelsize=8)
# plt.rc('axes', labelsize=8)
slc.save(file, mpl_kwargs={"figsize": [2, 2]})
elif method == "lic":
# velocyto_tex = runlic(V_grid, V_grid, 100)
# plot_LIC_gray(velocyto_tex)
pass
if save_show_or_return == "save":
s_kwargs = {"path": None, "prefix": 'line_integral_conv', "dpi": None,
"ext": 'pdf', "transparent": True, "close": True, "verbose": True}
s_kwargs = update_dict(s_kwargs, save_kwargs)
save_fig(**s_kwargs)
elif save_show_or_return == "show":
plt.tight_layout()
plt.show()
elif save_show_or_return == "return":
return slc
@docstrings.with_indent(4)
def cell_wise_vectors(
adata,
basis="umap",
x=0,
y=1,
color='ntr',
layer="X",
highlights=None,
labels=None,
values=None,
theme=None,
cmap=None,
color_key=None,
color_key_cmap=None,
background='white',
ncols=4,
pointsize=None,
figsize=(6, 4),
show_legend='on data',
use_smoothed=True,
ax=None,
sort='raw',
aggregate=None,
show_arrowed_spines=True,
inverse=False,
cell_ind="all",
quiver_size=None,
quiver_length=None,
vector='velocity',
frontier=False,
save_show_or_return='show',
save_kwargs={},
s_kwargs_dict={},
**cell_wise_kwargs,
):
"""Plot the velocity or acceleration vector of each cell.
Parameters
----------
%(scatters.parameters.no_show_legend|kwargs|save_kwargs)s
inverse: `bool` (default: False)
Whether to inverse the direction of the velocity vectors.
cell_ind: `str` or `list` (default: all)
the cell index that will be chosen to draw velocity vectors.
quiver_size: `float` or None (default: None)
The size of quiver. If None, we will use set quiver_size to be 1. Note that quiver quiver_size is used to calculate
the head_width (10 x quiver_size), head_length (12 x quiver_size) and headaxislength (8 x quiver_size) of the quiver.
This is done via the `default_quiver_args` function which also calculate the scale of the quiver (1 / quiver_length).
quiver_length: `float` or None (default: None)
The length of quiver. The quiver length which will be used to calculate scale of quiver. Note that befoe applying
`default_quiver_args` velocity values are first rescaled via the quiver_autoscaler function. Scale of quiver indicates
the nuumber of data units per arrow length unit, e.g., m/s per plot width; a smaller scale parameter makes the arrow longer.
vector: `str` (default: `velocity`)
Which vector type will be used for plotting, one of {'velocity', 'acceleration'} or either velocity field or
acceleration field will be plotted.
frontier: `bool` (default: `False`)
Whether to add the frontier. Scatter plots can be enhanced by using transparency (alpha) in order to show area
of high density and multiple scatter plots can be used to delineate a frontier. See matplotlib tips & tricks
cheatsheet (https://github.com/matplotlib/cheatsheets). Originally inspired by figures from scEU-seq paper:
https://science.sciencemag.org/content/367/6482/1151.
save_kwargs: `dict` (default: `{}`)
A dictionary that will passed to the save_fig function. By default it is an empty dictionary and the save_fig function
will use the {"path": None, "prefix": 'cell_wise_velocity', "dpi": None, "ext": 'pdf', "transparent": True, "close":
True, "verbose": True} as its parameters. Otherwise you can provide a dictionary that properly modify those keys
according to your needs.
s_kwargs_dict: `dict` (default: {})
The dictionary of the scatter arguments.
cell_wise_kwargs:
Additional parameters that will be passed to plt.quiver function
Returns
-------
Nothing but a cell wise quiver plot.
"""
import matplotlib.pyplot as plt
from matplotlib import rcParams
from matplotlib.colors import to_hex
if type(x) == str and type(y) == str:
if len(adata.var_names[adata.var.use_for_dynamics].intersection([x, y])) != 2:
raise ValueError(f'If you want to plot the vector flow of two genes, please make sure those two genes '
f'belongs to dynamics genes or .var.use_for_dynamics is True.')
X = adata[:, [x, y]].layers['M_s'].A
V = adata[:, [x, y]].layers['velocity_S'].A
else:
if ("X_" + basis in adata.obsm.keys()) and (
vector + "_" + basis in adata.obsm.keys()
):
X = adata.obsm["X_" + basis][:, [x, y]]
V = adata.obsm[vector + "_" + basis][:, [x, y]]
else:
if "X_" + basis not in adata.obsm.keys():
layer, basis = basis.split("_")
reduceDimension(adata, layer=layer, reduction_method=basis)
if "kmc" not in adata.uns_keys():
cell_velocities(adata, vkey="velocity_S", basis=basis)
X = adata.obsm["X_" + basis][:, [x, y]]
V = adata.obsm[vector + "_" + basis][:, [x, y]]
else:
kmc = adata.uns["kmc"]
X = adata.obsm["X_" + basis][:, [x, y]]
V = kmc.compute_density_corrected_drift(X, kmc.Idx, normalize_vector=True)
adata.obsm[vector + "_" + basis] = V
V /= 3 * quiver_autoscaler(X, V)
if inverse: V = -V
df = pd.DataFrame({"x": X[:, 0], "y": X[:, 1], "u": V[:, 0], "v": V[:, 1]})
if background is None:
_background = rcParams.get("figure.facecolor")
background = to_hex(_background) if type(_background) is tuple else _background
if quiver_size is None:
quiver_size = 1
if background == "black":
edgecolors = "white"
else:
edgecolors = "black"
head_w, head_l, ax_l, scale = default_quiver_args(quiver_size, quiver_length) #
quiver_kwargs = {
"angles": "xy",
"scale": scale,
"scale_units": "xy",
"width": 0.0005,
"headwidth": head_w,
"headlength": head_l,
"headaxislength": ax_l,
"minshaft": 1,
"minlength": 1,
"pivot": "tail",
"linewidth": 0.1,
"edgecolors": edgecolors,
"alpha": 1,
"zorder": 10,
}
quiver_kwargs = update_dict(quiver_kwargs, cell_wise_kwargs)
# if ax is None:
# plt.figure(facecolor=background)
axes_list, color_list, _ = scatters(
adata=adata,
basis=basis,
x=x,
y=y,
color=color,
layer=layer,
highlights=highlights,
labels=labels,
values=values,
theme=theme,
cmap=cmap,
color_key=color_key,
color_key_cmap=color_key_cmap,
background=background,
ncols=ncols,
pointsize=pointsize,
figsize=figsize,
show_legend=show_legend,
use_smoothed=use_smoothed,
aggregate=aggregate,
show_arrowed_spines=show_arrowed_spines,
ax=ax,
sort=sort,
save_show_or_return="return",
frontier=frontier,
**s_kwargs_dict,
return_all=True,
)
if cell_ind == "all":
ix_choice = np.arange(adata.shape[0])
elif cell_ind == "random":
ix_choice = np.random.choice(np.range(adata.shape[0]), size=1000, replace=False)
elif type(cell_ind) is int:
ix_choice = np.random.choice(
np.range(adata.shape[0]), size=cell_ind, replace=False
)
elif type(cell_ind) is list:
ix_choice = cell_ind
if type(axes_list) == list:
for i in range(len(axes_list)):
axes_list[i].quiver(
df.iloc[ix_choice, 0],
df.iloc[ix_choice, 1],
df.iloc[ix_choice, 2],
df.iloc[ix_choice, 3],
color=color_list[i],
facecolors=color_list[i],
**quiver_kwargs,
)
axes_list[i].set_facecolor(background)
else:
axes_list.quiver(
df.iloc[ix_choice, 0],
df.iloc[ix_choice, 1],
df.iloc[ix_choice, 2],
df.iloc[ix_choice, 3],
color=color_list,
facecolors=color_list,
**quiver_kwargs,
)
axes_list.set_facecolor(background)
if save_show_or_return == "save":
s_kwargs = {"path": None, "prefix": 'cell_wise_vector', "dpi": None,
"ext": 'pdf', "transparent": True, "close": True, "verbose": True}
s_kwargs = update_dict(s_kwargs, save_kwargs)
save_fig(**s_kwargs)
elif save_show_or_return == "show":
plt.tight_layout()
plt.show()
elif save_show_or_return == "return":
return axes_list
@docstrings.with_indent(4)
def grid_vectors(
adata,
basis="umap",
x=0,
y=1,
color='ntr',
layer="X",
highlights=None,
labels=None,
values=None,
theme=None,
cmap=None,
color_key=None,
color_key_cmap=None,
background='white',
ncols=4,
pointsize=None,
figsize=(6, 4),
show_legend='on data',
use_smoothed=True,
ax=None,
sort='raw',
aggregate=None,
show_arrowed_spines=True,
inverse=False,
method="gaussian",
xy_grid_nums=[50, 50],
cut_off_velocity=True,
quiver_size=None,
quiver_length=None,
vector='velocity',
frontier=False,
save_show_or_return='show',
save_kwargs={},
s_kwargs_dict={},
q_kwargs_dict={},
**grid_kwargs,
):
"""Plot the velocity or acceleration vector of each cell on a grid.
Parameters
----------
%(scatters.parameters.no_show_legend|kwargs|save_kwargs)s
inverse: `bool` (default: False)
Whether to inverse the direction of the velocity vectors.
method: `str` (default: `SparseVFC`)
Method to reconstruct the vector field. Currently it supports either SparseVFC (default) or the empirical method
Gaussian kernel method from RNA velocity (Gaussian).
xy_grid_nums: `tuple` (default: (50, 50))
the number of grids in either x or y axis.
cut_off_velocity: `bool` (default: True)
Whether to remove small velocity vectors from the recovered the vector field grid, either through the simple
Gaussian kernel (applicable to 2D) or the powerful sparseVFC approach.
quiver_size: `float` or None (default: None)
The size of quiver. If None, we will use set quiver_size to be 1. Note that quiver quiver_size is used to calculate
the head_width (10 x quiver_size), head_length (12 x quiver_size) and headaxislength (8 x quiver_size) of the quiver.
This is done via the `default_quiver_args` function which also calculate the scale of the quiver (1 / quiver_length).
quiver_length: `float` or None (default: None)
The length of quiver. The quiver length which will be used to calculate scale of quiver. Note that befoe applying
`default_quiver_args` velocity values are first rescaled via the quiver_autoscaler function. Scale of quiver indicates
the nuumber of data units per arrow length unit, e.g., m/s per plot width; a smaller scale parameter makes the arrow longer.
vector: `str` (default: `velocity`)
Which vector type will be used for plotting, one of {'velocity', 'acceleration'} or either velocity field or
acceleration field will be plotted.
frontier: `bool` (default: `False`)
Whether to add the frontier. Scatter plots can be enhanced by using transparency (alpha) in order to show area
of high density and multiple scatter plots can be used to delineate a frontier. See matplotlib tips & tricks
cheatsheet (https://github.com/matplotlib/cheatsheets). Originally inspired by figures from scEU-seq paper:
https://science.sciencemag.org/content/367/6482/1151.
save_kwargs: `dict` (default: `{}`)
A dictionary that will passed to the save_fig function. By default it is an empty dictionary and the save_fig function
will use the {"path": None, "prefix": 'grid_velocity', "dpi": None, "ext": 'pdf', "transparent": True, "close":
True, "verbose": True} as its parameters. Otherwise you can provide a dictionary that properly modify those keys
according to your needs.
s_kwargs_dict: `dict` (default: {})
The dictionary of the scatter arguments.
q_kwargs_dict: `dict` (default: {})
The dictionary of the quiver arguments.
grid_kwargs:
Additional parameters that will be passed to velocity_on_grid function.
Returns
-------
Nothing but a quiver plot on the grid.
"""
import matplotlib.pyplot as plt
from matplotlib import rcParams
from matplotlib.colors import to_hex
if type(x) == str and type(y) == str:
if len(adata.var_names[adata.var.use_for_dynamics].intersection([x, y])) != 2:
raise ValueError(f'If you want to plot the vector flow of two genes, please make sure those two genes '
f'belongs to dynamics genes or .var.use_for_dynamics is True.')
X = adata[:, [x, y]].layers['M_s'].A
V = adata[:, [x, y]].layers['velocity_S'].A
else:
if ("X_" + basis in adata.obsm.keys()) and (
vector + '_' + basis in adata.obsm.keys()
):
X = adata.obsm["X_" + basis][:, [x, y]]
V = adata.obsm[vector + '_' + basis][:, [x, y]]
else:
if "X_" + basis not in adata.obsm.keys():
layer, basis = basis.split("_")
reduceDimension(adata, layer=layer, reduction_method=basis)
if "kmc" not in adata.uns_keys():
cell_velocities(adata, vkey="velocity_S", basis=basis)
X = adata.obsm["X_" + basis][:, [x, y]]
V = adata.obsm[vector + '_' + basis][:, [x, y]]
else:
kmc = adata.uns["kmc"]
X = adata.obsm["X_" + basis][:, [x, y]]
V = kmc.compute_density_corrected_drift(X, kmc.Idx, normalize_vector=True)
adata.obsm[vector + '_' + basis] = V
grid_kwargs_dict = {
"density": None,
"smooth": None,
"n_neighbors": None,
"min_mass": None,
"autoscale": False,
"adjust_for_stream": True,
"V_threshold": None,
}
grid_kwargs_dict = update_dict(grid_kwargs_dict, grid_kwargs)
if method.lower() == "sparsevfc":
if "VecFld_" + basis not in adata.uns.keys():
VectorField(adata, basis=basis, dims=[x, y])
X_grid, V_grid = (
adata.uns["VecFld_" + basis]["VecFld"]["grid"],
adata.uns["VecFld_" + basis]["VecFld"]["grid_V"],
)
N = int(np.sqrt(V_grid.shape[0]))
if cut_off_velocity:
X_grid, p_mass, neighs, weight = prepare_velocity_grid_data(X,
xy_grid_nums,
density=grid_kwargs_dict['density'],
smooth=grid_kwargs_dict['smooth'],
n_neighbors=grid_kwargs_dict['n_neighbors'], )
for i in ['density', 'smooth', 'n_neighbors']:
grid_kwargs_dict.pop(i)
VecFld, func = vecfld_from_adata(adata, basis)
V_emb = func(X)
V_grid = (V_emb[neighs] * weight[:, :, None]).sum(1) / np.maximum(1, p_mass)[:, None]
X_grid, V_grid = grid_velocity_filter(
V_emb=V,
neighs=neighs,
p_mass=p_mass,
X_grid=X_grid,
V_grid=V_grid,
**grid_kwargs_dict
)
else:
X_grid, V_grid = (
np.array([np.unique(X_grid[:, 0]), np.unique(X_grid[:, 1])]),
np.array([V_grid[:, 0].reshape((N, N)), V_grid[:, 1].reshape((N, N))]),
)
elif method.lower() == "gaussian":
X_grid, V_grid, D = velocity_on_grid(
X, V, xy_grid_nums, cut_off_velocity=cut_off_velocity, **grid_kwargs_dict
)
elif "grid_velocity_" + basis in adata.uns.keys():
X_grid, V_grid, _ = (
adata.uns["grid_velocity_" + basis]["VecFld"]["X_grid"],
adata.uns["grid_velocity_" + basis]["VecFld"]["V_grid"],
adata.uns["grid_velocity_" + basis]["VecFld"]["D"],
)
else:
raise Exception(
"Vector field learning method {} is not supported or the grid velocity is collected for "
"the current adata object.".format(method)
)
V_grid /= 3 * quiver_autoscaler(X_grid, V_grid)
if inverse: V_grid = -V_grid
if background is None:
_background = rcParams.get("figure.facecolor")
background = to_hex(_background) if type(_background) is tuple else _background
if quiver_size is None:
quiver_size = 1
if background == "black":
edgecolors = "white"
else:
edgecolors = "black"
head_w, head_l, ax_l, scale = default_quiver_args(quiver_size, quiver_length)
quiver_kwargs = {
"angles": "xy",
"scale": scale,
"scale_units": "xy",
"width": 0.0005,
"headwidth": head_w,
"headlength": head_l,
"headaxislength": ax_l,
"minshaft": 1,
"minlength": 1,
"pivot": "tail",
"edgecolors": edgecolors,
"linewidth": 0.2,
"facecolors": edgecolors,
"color": edgecolors,
"alpha": 1,
"zorder": 3,
}
quiver_kwargs = update_dict(quiver_kwargs, q_kwargs_dict)
# if ax is None:
# plt.figure(facecolor=background)
axes_list, _, font_color = scatters(
adata=adata,
basis=basis,
x=x,
y=y,
color=color,
layer=layer,
highlights=highlights,
labels=labels,
values=values,
theme=theme,
cmap=cmap,
color_key=color_key,
color_key_cmap=color_key_cmap,
background=background,
ncols=ncols,
pointsize=pointsize,
figsize=figsize,
show_legend=show_legend,
use_smoothed=use_smoothed,
aggregate=aggregate,
show_arrowed_spines=show_arrowed_spines,
ax=ax,
sort=sort,
save_show_or_return="return",
frontier=frontier,
**s_kwargs_dict,
return_all=True,
)
if type(axes_list) == list:
for i in range(len(axes_list)):
axes_list[i].quiver(
X_grid[0], X_grid[1], V_grid[0], V_grid[1], **quiver_kwargs
)
axes_list[i].set_facecolor(background)
else:
axes_list.quiver(
X_grid[0], X_grid[1], V_grid[0], V_grid[1], **quiver_kwargs
)
axes_list.set_facecolor(background)
if save_show_or_return == "save":
s_kwargs = {"path": None, "prefix": 'grid_velocity', "dpi": None,
"ext": 'pdf', "transparent": True, "close": True, "verbose": True}
s_kwargs = update_dict(s_kwargs, save_kwargs)
save_fig(**s_kwargs)
elif save_show_or_return == "show":
plt.tight_layout()
plt.show()
elif save_show_or_return == "return":
return axes_list
@docstrings.with_indent(4)
def streamline_plot(
adata,
basis="umap",
x=0,
y=1,
color='ntr',
layer="X",
highlights=None,
labels=None,
values=None,
theme=None,
cmap=None,
color_key=None,
color_key_cmap=None,
background='white',
ncols=4,
pointsize=None,
figsize=(6, 4),
show_legend='on data',
use_smoothed=True,
ax=None,
sort='raw',
aggregate=None,
show_arrowed_spines=True,
inverse=False,
method="gaussian",
xy_grid_nums=[50, 50],
cut_off_velocity=True,
density=1,
linewidth=1,
streamline_alpha=1,
vector='velocity',
frontier=False,
save_show_or_return='show',
save_kwargs={},
s_kwargs_dict={},
**streamline_kwargs,
):
"""Plot the velocity vector of each cell.
Parameters
----------
%(scatters.parameters.no_show_legend|kwargs|save_kwargs)s
inverse: `bool` (default: False)
Whether to inverse the direction of the velocity vectors.
method: `str` (default: `SparseVFC`)
Method to reconstruct the vector field. Currently it supports either SparseVFC (default) or the empirical method
Gaussian kernel method from RNA velocity (Gaussian).
xy_grid_nums: `tuple` (default: (50, 50))
the number of grids in either x or y axis.
cut_off_velocity: `bool` (default: True)
Whether to remove small velocity vectors from the recovered the vector field grid, either through the simple
Gaussian kernel (applicable only to 2D) or the powerful sparseVFC approach.
density: `float` or None (default: 1)
density of the plt.streamplot function.
linewidth: `float` or None (default: 1)
multiplier of automatically calculated linewidth passed to the plt.streamplot function.
streamline_alpha: `float` or None (default: 1)
The alpha value applied to the vector field stream lines.
vector: `str` (default: `velocity`)
Which vector type will be used for plotting, one of {'velocity', 'acceleration'} or either velocity field or
acceleration field will be plotted.
frontier: `bool` (default: `False`)
Whether to add the frontier. Scatter plots can be enhanced by using transparency (alpha) in order to show area
of high density and multiple scatter plots can be used to delineate a frontier. See matplotlib tips & tricks
cheatsheet (https://github.com/matplotlib/cheatsheets). Originally inspired by figures from scEU-seq paper:
https://science.sciencemag.org/content/367/6482/1151.
save_kwargs: `dict` (default: `{}`)
A dictionary that will passed to the save_fig function. By default it is an empty dictionary and the save_fig function
will use the {"path": None, "prefix": 'streamline_plot', "dpi": None, "ext": 'pdf', "transparent": True, "close":
True, "verbose": True} as its parameters. Otherwise you can provide a dictionary that properly modify those keys
according to your needs.
s_kwargs_dict: `dict` (default: {})
The dictionary of the scatter arguments.
streamline_kwargs:
Additional parameters that will be passed to plt.streamplot function
Returns
-------
Nothing but a streamline plot that integrates paths in the vector field.
"""
import matplotlib.pyplot as plt
from matplotlib import rcParams
from matplotlib.colors import to_hex
if type(x) == str and type(y) == str:
if len(adata.var_names[adata.var.use_for_dynamics].intersection([x, y])) != 2:
raise ValueError(f'If you want to plot the vector flow of two genes, please make sure those two genes '
f'belongs to dynamics genes or .var.use_for_dynamics is True.')
X = adata[:, [x, y]].layers['M_s'].A
V = adata[:, [x, y]].layers['velocity_S'].A
else:
if ("X_" + basis in adata.obsm.keys()) and (
vector + "_" + basis in adata.obsm.keys()
):
X = adata.obsm["X_" + basis][:, [x, y]]
V = adata.obsm[vector + '_' + basis][:, [x, y]]
else:
if "X_" + basis not in adata.obsm.keys():
layer, basis = basis.split("_")
reduceDimension(adata, layer=layer, reduction_method=basis)
if "kmc" not in adata.uns_keys():
cell_velocities(adata, vkey="velocity_S", basis=basis)
X = adata.obsm["X_" + basis][:, [x, y]]
V = adata.obsm[vector + '_' + basis][:, [x, y]]
else:
kmc = adata.uns["kmc"]
X = adata.obsm["X_" + basis][:, [x, y]]
V = kmc.compute_density_corrected_drift(X, kmc.Idx, normalize_vector=True)
adata.obsm[vector + '_' + basis] = V
grid_kwargs_dict = {
"density": None,
"smooth": None,
"n_neighbors": None,
"min_mass": None,
"autoscale": False,
"adjust_for_stream": True,
"V_threshold": None,
}
grid_kwargs_dict = update_dict(grid_kwargs_dict, streamline_kwargs)
if method.lower() == "sparsevfc":
if "VecFld_" + basis not in adata.uns.keys():
VectorField(adata, basis=basis, dims=[x, y])
X_grid, V_grid = (
adata.uns["VecFld_" + basis]["VecFld"]["grid"],
adata.uns["VecFld_" + basis]["VecFld"]["grid_V"],
)
N = int(np.sqrt(V_grid.shape[0]))
if cut_off_velocity:
X_grid, p_mass, neighs, weight = prepare_velocity_grid_data(X,
xy_grid_nums,
density=grid_kwargs_dict['density'],
smooth=grid_kwargs_dict['smooth'],
n_neighbors=grid_kwargs_dict['n_neighbors'], )
for i in ['density', 'smooth', 'n_neighbors']:
grid_kwargs_dict.pop(i)
VecFld, func = vecfld_from_adata(adata, basis)
V_emb = func(X)
V_grid = (V_emb[neighs] * weight[:, :, None]).sum(1) / np.maximum(1, p_mass)[:, None]
X_grid, V_grid = grid_velocity_filter(
V_emb=V,
neighs=neighs,
p_mass=p_mass,
X_grid=X_grid,
V_grid=V_grid,
**grid_kwargs_dict
)
else:
X_grid, V_grid = (
np.array([np.unique(X_grid[:, 0]), np.unique(X_grid[:, 1])]),
np.array([V_grid[:, 0].reshape((N, N)), V_grid[:, 1].reshape((N, N))]),
)
elif method.lower() == "gaussian":
X_grid, V_grid, D = velocity_on_grid(
X, V, xy_grid_nums, cut_off_velocity=cut_off_velocity, **grid_kwargs_dict
)
elif "grid_velocity_" + basis in adata.uns.keys():
X_grid, V_grid, _ = (
adata.uns["grid_velocity_" + basis]["VecFld"]["X_grid"],
adata.uns["grid_velocity_" + basis]["VecFld"]["V_grid"],
adata.uns["grid_velocity_" + basis]["VecFld"]["D"],
)
else:
raise Exception(
"Vector field learning method {} is not supported or the grid velocity is collected for "
"the current adata object.".format(method)
)
if inverse: V_grid = -V_grid
streamplot_kwargs = {
"density": density * 2,
"linewidth": None,
"cmap": None,
"norm": None,
"arrowsize": 1,
"arrowstyle": "fancy",
"minlength": 0.1,
"transform": None,
"start_points": None,
"maxlength": 4.0,
"integration_direction": "both",
"zorder": 3,
}
mass = np.sqrt((V_grid ** 2).sum(0))
linewidth *= 2 * mass / mass[~np.isnan(mass)].max()
streamplot_kwargs.update({"linewidth": linewidth})
streamplot_kwargs = update_dict(streamplot_kwargs, streamline_kwargs)
if background is None:
_background = rcParams.get("figure.facecolor")
background = to_hex(_background) if type(_background) is tuple else _background
if background in ["black", "#ffffff"]:
streamline_color = "red"
else:
streamline_color = "black"
# if ax is None:
# plt.figure(facecolor=background)
axes_list, _, _ = scatters(
adata=adata,
basis=basis,
x=x,
y=y,
color=color,
layer=layer,
highlights=highlights,
labels=labels,
values=values,
theme=theme,
cmap=cmap,
color_key=color_key,
color_key_cmap=color_key_cmap,
background=background,
ncols=ncols,
pointsize=pointsize,
figsize=figsize,
show_legend=show_legend,
use_smoothed=use_smoothed,
aggregate=aggregate,
show_arrowed_spines=show_arrowed_spines,
ax=ax,
sort=sort,
save_show_or_return="return",
frontier=frontier,
**s_kwargs_dict,
return_all=True,
)
if type(axes_list) == list:
for i in range(len(axes_list)):
axes_list[i].set_facecolor(background)
s = axes_list[i].streamplot(
X_grid[0],
X_grid[1],
V_grid[0],
V_grid[1],
color=streamline_color,
**streamplot_kwargs,
)
set_arrow_alpha(axes_list[i], streamline_alpha)
set_stream_line_alpha(s, streamline_alpha)
else:
axes_list.set_facecolor(background)
s = axes_list.streamplot(
X_grid[0],
X_grid[1],
V_grid[0],
V_grid[1],
color=streamline_color,
**streamplot_kwargs,
)
set_arrow_alpha(axes_list, streamline_alpha)
set_stream_line_alpha(s, streamline_alpha)
if save_show_or_return == "save":
s_kwargs = {"path": None, "prefix": 'streamline_plot', "dpi": None,
"ext": 'pdf', "transparent": True, "close": True, "verbose": True}
s_kwargs = update_dict(s_kwargs, save_kwargs)
save_fig(**s_kwargs)
elif save_show_or_return == "show":
plt.tight_layout()
plt.show()
elif save_show_or_return == "return":
return axes_list
# refactor line_conv_integration
def plot_energy(adata,
basis=None,
vecfld_dict=None,
figsize=None,
fig=None,
save_show_or_return='show',
save_kwargs={},
):
"""Plot the energy and energy change rate over each optimization iteration.
Parameters
----------
adata: :class:`~anndata.AnnData`
an Annodata object with vector field function reconstructed.
basis: `str` or None (default: `None`)
The reduced dimension embedding (pca or umap, for example) of cells from which vector field function was
reconstructed. When basis is None, the velocity vector field function building from the full gene expression
space is used.
vecfld_dict: `str` or None (default: `None`)
The dictionary storing the information for the reconstructed velocity vector field function. If None, the
corresponding dictionary stored in the adata object will be used.
figsize: `[float, float]` or `None` (default: None)
The width and height of the resulting figure when fig is set to be None.
fig: `matplotlib.figure.Figure` or None
The figure object where panels of the energy or energy change rate over iteration plots will be appended to.
save_show_or_return: {'show', 'save', 'return'} (default: `show`)
Whether to save, show or return the figure.
save_kwargs: `dict` (default: `{}`)
A dictionary that will passed to the save_fig function. By default it is an empty dictionary and the save_fig
function will use the {"path": None, "prefix": 'energy', "dpi": None, "ext": 'pdf', "transparent": True, "close":
True, "verbose": True} as its parameters. Otherwise you can provide a dictionary that properly modify those
keys according to your needs.
Returns
-------
Nothing, but plot the energy or energy change rate each optimization iteration.
"""
import matplotlib.pyplot as plt
if vecfld_dict is None:
vf_key = 'VecFld' if basis is None else 'VecFld_' + basis
if vf_key not in adata.uns.keys():
raise ValueError(f"Your adata doesn't have the key for Vector Field with {basis} basis."
f"Try firstly running dyn.tl.VectorField(adata, basis={basis}).")
vecfld_dict = adata.uns[vf_key]
E = vecfld_dict['VecFld']['E_traj'] if 'E_traj' in vecfld_dict['VecFld'] else None
tecr = vecfld_dict['VecFld']['tecr_traj'] if 'tecr_traj' in vecfld_dict['VecFld'] else None
if E is not None and tecr is not None:
fig = fig or plt.figure(figsize=figsize)
Iterations = np.arange(0, len(E))
ax = fig.add_subplot(1, 2, 1)
E_ = E - np.min(E) + 1
ax.plot(Iterations, E_, 'k')
ax.plot(E_, 'r.')
ax.set_yscale("log")
plt.xlabel('Iteration')
plt.ylabel('Energy')
ax = fig.add_subplot(1, 2, 2)
ax.plot(Iterations, tecr, 'k')
ax.plot(tecr, 'r.')
ax.set_yscale("log")
plt.xlabel('Iteration')
plt.ylabel('Energy change rate')
if save_show_or_return == "save":
s_kwargs = {"path": None, "prefix": 'energy', "dpi": None,
"ext": 'pdf', "transparent": True, "close": True, "verbose": True}
s_kwargs = update_dict(s_kwargs, save_kwargs)
save_fig(**s_kwargs)
elif save_show_or_return == "show":
plt.tight_layout()
plt.show()
elif save_show_or_return == "return":
return fig
| [
"numpy.range",
"numpy.maximum",
"numpy.empty",
"numpy.isnan",
"matplotlib.pyplot.figure",
"yt.SlicePlot",
"numpy.arange",
"matplotlib.colors.to_hex",
"matplotlib.pyplot.tight_layout",
"numpy.unique",
"pandas.DataFrame",
"matplotlib.pyplot.imshow",
"numpy.reshape",
"yt.load_uniform_grid",
... | [((1957, 1988), 'numpy.empty', 'np.empty', (['(M, N, 4)', 'np.float32'], {}), '((M, N, 4), np.float32)\n', (1965, 1988), True, 'import numpy as np\n'), ((2154, 2166), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (2164, 2166), True, 'import matplotlib.pyplot as plt\n'), ((2171, 2190), 'matplotlib.pyplot.imshow', 'plt.imshow', (['texture'], {}), '(texture)\n', (2181, 2190), True, 'import matplotlib.pyplot as plt\n'), ((15812, 15882), 'pandas.DataFrame', 'pd.DataFrame', (["{'x': X[:, 0], 'y': X[:, 1], 'u': V[:, 0], 'v': V[:, 1]}"], {}), "({'x': X[:, 0], 'y': X[:, 1], 'u': V[:, 0], 'v': V[:, 1]})\n", (15824, 15882), True, 'import pandas as pd\n'), ((8718, 8786), 'numpy.repeat', 'np.repeat', (['velocity_x_ori[:, :, np.newaxis]', 'V_grid.shape[1]'], {'axis': '(2)'}), '(velocity_x_ori[:, :, np.newaxis], V_grid.shape[1], axis=2)\n', (8727, 8786), True, 'import numpy as np\n'), ((8830, 8898), 'numpy.repeat', 'np.repeat', (['velocity_y_ori[:, :, np.newaxis]', 'V_grid.shape[1]'], {'axis': '(2)'}), '(velocity_y_ori[:, :, np.newaxis], V_grid.shape[1], axis=2)\n', (8839, 8898), True, 'import numpy as np\n'), ((8942, 9010), 'numpy.repeat', 'np.repeat', (['velocity_z_ori[np.newaxis, :, :]', 'V_grid.shape[1]'], {'axis': '(0)'}), '(velocity_z_ori[np.newaxis, :, :], V_grid.shape[1], axis=0)\n', (8951, 9010), True, 'import numpy as np\n'), ((9301, 9386), 'yt.load_uniform_grid', 'yt.load_uniform_grid', (['data', "data['velocity_x'][0].shape"], {'length_unit': "(1.0, 'Mpc')"}), "(data, data['velocity_x'][0].shape, length_unit=(1.0,\n 'Mpc'))\n", (9321, 9386), False, 'import yt\n'), ((9419, 9458), 'yt.SlicePlot', 'yt.SlicePlot', (['ds', '"""z"""', "['velocity_sum']"], {}), "(ds, 'z', ['velocity_sum'])\n", (9431, 9458), False, 'import yt\n'), ((15933, 15965), 'matplotlib.rcParams.get', 'rcParams.get', (['"""figure.facecolor"""'], {}), "('figure.facecolor')\n", (15945, 15965), False, 'from matplotlib import rcParams\n'), ((17606, 17631), 'numpy.arange', 'np.arange', (['adata.shape[0]'], {}), '(adata.shape[0])\n', (17615, 17631), True, 'import numpy as np\n'), ((27410, 27442), 'matplotlib.rcParams.get', 'rcParams.get', (['"""figure.facecolor"""'], {}), "('figure.facecolor')\n", (27422, 27442), False, 'from matplotlib import rcParams\n'), ((38125, 38157), 'matplotlib.rcParams.get', 'rcParams.get', (['"""figure.facecolor"""'], {}), "('figure.facecolor')\n", (38137, 38157), False, 'from matplotlib import rcParams\n'), ((43426, 43449), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Iteration"""'], {}), "('Iteration')\n", (43436, 43449), True, 'import matplotlib.pyplot as plt\n'), ((43458, 43478), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Energy"""'], {}), "('Energy')\n", (43468, 43478), True, 'import matplotlib.pyplot as plt\n'), ((43622, 43645), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Iteration"""'], {}), "('Iteration')\n", (43632, 43645), True, 'import matplotlib.pyplot as plt\n'), ((43654, 43686), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Energy change rate"""'], {}), "('Energy change rate')\n", (43664, 43686), True, 'import matplotlib.pyplot as plt\n'), ((8663, 8685), 'numpy.zeros', 'np.zeros', (['U_grid.shape'], {}), '(U_grid.shape)\n', (8671, 8685), True, 'import numpy as np\n'), ((9235, 9277), 'numpy.sqrt', 'np.sqrt', (['(velocity_x ** 2 + velocity_y ** 2)'], {}), '(velocity_x ** 2 + velocity_y ** 2)\n', (9242, 9277), True, 'import numpy as np\n'), ((10757, 10775), 'matplotlib.pyplot.tight_layout', 'plt.tight_layout', ([], {}), '()\n', (10773, 10775), True, 'import matplotlib.pyplot as plt\n'), ((10784, 10794), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (10792, 10794), True, 'import matplotlib.pyplot as plt\n'), ((15987, 16006), 'matplotlib.colors.to_hex', 'to_hex', (['_background'], {}), '(_background)\n', (15993, 16006), False, 'from matplotlib.colors import to_hex\n'), ((19059, 19077), 'matplotlib.pyplot.tight_layout', 'plt.tight_layout', ([], {}), '()\n', (19075, 19077), True, 'import matplotlib.pyplot as plt\n'), ((19086, 19096), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (19094, 19096), True, 'import matplotlib.pyplot as plt\n'), ((25314, 25338), 'numpy.sqrt', 'np.sqrt', (['V_grid.shape[0]'], {}), '(V_grid.shape[0])\n', (25321, 25338), True, 'import numpy as np\n'), ((27464, 27483), 'matplotlib.colors.to_hex', 'to_hex', (['_background'], {}), '(_background)\n', (27470, 27483), False, 'from matplotlib.colors import to_hex\n'), ((29833, 29851), 'matplotlib.pyplot.tight_layout', 'plt.tight_layout', ([], {}), '()\n', (29849, 29851), True, 'import matplotlib.pyplot as plt\n'), ((29860, 29870), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (29868, 29870), True, 'import matplotlib.pyplot as plt\n'), ((35492, 35516), 'numpy.sqrt', 'np.sqrt', (['V_grid.shape[0]'], {}), '(V_grid.shape[0])\n', (35499, 35516), True, 'import numpy as np\n'), ((38179, 38198), 'matplotlib.colors.to_hex', 'to_hex', (['_background'], {}), '(_background)\n', (38185, 38198), False, 'from matplotlib.colors import to_hex\n'), ((40343, 40361), 'matplotlib.pyplot.tight_layout', 'plt.tight_layout', ([], {}), '()\n', (40359, 40361), True, 'import matplotlib.pyplot as plt\n'), ((40370, 40380), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (40378, 40380), True, 'import matplotlib.pyplot as plt\n'), ((43186, 43213), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': 'figsize'}), '(figsize=figsize)\n', (43196, 43213), True, 'import matplotlib.pyplot as plt\n'), ((44012, 44030), 'matplotlib.pyplot.tight_layout', 'plt.tight_layout', ([], {}), '()\n', (44028, 44030), True, 'import matplotlib.pyplot as plt\n'), ((44039, 44049), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (44047, 44049), True, 'import matplotlib.pyplot as plt\n'), ((6818, 6842), 'numpy.sqrt', 'np.sqrt', (['V_grid.shape[0]'], {}), '(V_grid.shape[0])\n', (6825, 6842), True, 'import numpy as np\n'), ((6865, 6897), 'numpy.reshape', 'np.reshape', (['V_grid[:, 0]', '(N, N)'], {}), '(V_grid[:, 0], (N, N))\n', (6875, 6897), True, 'import numpy as np\n'), ((6921, 6953), 'numpy.reshape', 'np.reshape', (['V_grid[:, 1]', '(N, N)'], {}), '(V_grid[:, 1], (N, N))\n', (6931, 6953), True, 'import numpy as np\n'), ((17700, 17724), 'numpy.range', 'np.range', (['adata.shape[0]'], {}), '(adata.shape[0])\n', (17708, 17724), True, 'import numpy as np\n'), ((43312, 43321), 'numpy.min', 'np.min', (['E'], {}), '(E)\n', (43318, 43321), True, 'import numpy as np\n'), ((17834, 17858), 'numpy.range', 'np.range', (['adata.shape[0]'], {}), '(adata.shape[0])\n', (17842, 17858), True, 'import numpy as np\n'), ((26089, 26110), 'numpy.maximum', 'np.maximum', (['(1)', 'p_mass'], {}), '(1, p_mass)\n', (26099, 26110), True, 'import numpy as np\n'), ((36267, 36288), 'numpy.maximum', 'np.maximum', (['(1)', 'p_mass'], {}), '(1, p_mass)\n', (36277, 36288), True, 'import numpy as np\n'), ((26440, 26463), 'numpy.unique', 'np.unique', (['X_grid[:, 0]'], {}), '(X_grid[:, 0])\n', (26449, 26463), True, 'import numpy as np\n'), ((26465, 26488), 'numpy.unique', 'np.unique', (['X_grid[:, 1]'], {}), '(X_grid[:, 1])\n', (26474, 26488), True, 'import numpy as np\n'), ((36618, 36641), 'numpy.unique', 'np.unique', (['X_grid[:, 0]'], {}), '(X_grid[:, 0])\n', (36627, 36641), True, 'import numpy as np\n'), ((36643, 36666), 'numpy.unique', 'np.unique', (['X_grid[:, 1]'], {}), '(X_grid[:, 1])\n', (36652, 36666), True, 'import numpy as np\n'), ((37923, 37937), 'numpy.isnan', 'np.isnan', (['mass'], {}), '(mass)\n', (37931, 37937), True, 'import numpy as np\n')] |
#This code can only train with M==1, because when M=1, lower bound and the true object are same
#from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import matplotlib
matplotlib.use('Agg')
import numpy as np
import os
import sys
import seaborn as sns
import scipy.spatial.distance
from matplotlib import pyplot as plt
import pandas as pd
import scipy.stats as stats
import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
import pickle
slim=tf.contrib.slim
Bernoulli = tf.contrib.distributions.Bernoulli
#%%
def bernoulli_loglikelihood(b, log_alpha):
return b * (-tf.nn.softplus(-log_alpha)) + (1 - b) * (-log_alpha - tf.nn.softplus(-log_alpha))
def lrelu(x, alpha=0.2):
return tf.nn.relu(x) - alpha * tf.nn.relu(-x)
def encoder1(x,bi_dim,reuse=False):
#return logits #<NAME> uses [512,256]
with tf.variable_scope("encoder") as scope:
if reuse:
scope.reuse_variables()
log_alpha1 = tf.layers.dense(x*2-1, bi_dim, name="encoder_1")
return log_alpha1
def encoder2(b1,bi_dim,reuse=False):
#return logits #<NAME> uses [512,256]
with tf.variable_scope("encoder") as scope:
if reuse:
scope.reuse_variables()
log_alpha2 = tf.layers.dense(b1*2-1, bi_dim, name="encoder_3")
return log_alpha2
def decoder(b2,x_dim,reuse=False):
#return logits
with tf.variable_scope("decoder") as scope:
if reuse:
scope.reuse_variables()
log_alphax = tf.layers.dense(b2*2-1, x_dim, None, name="decoder_1")
return log_alphax
def fun(x_lower,E2,axis_dim=2,reuse_encoder=False,reuse_decoder=False):
'''
x_star,E are N*(d_x or 2*d_bi)
calculate log p(x_star|E) + log p(E) - log q(E|x_star)
axis_dim is axis for d_x or d_b
x_star is observe x; E is latent b
return LogLik, N*M
'''
#log p(x_star|E), x_dim is global
log_alpha_x = decoder(E2,x_dim,reuse=reuse_decoder)
log_p_x_given_b2 = bernoulli_loglikelihood(x_lower, log_alpha_x)
log_p_x_given_b2 = tf.reduce_sum(log_p_x_given_b2, axis=axis_dim)
return -log_p_x_given_b2
def fig_gnrt(figs,epoch,show=False,bny=True,name_fig=None):
'''
input:N*28*28
'''
sns.set_style("whitegrid", {'axes.grid' : False})
plt.ioff()
if bny:
b = figs > 0.5
figs = b.astype('float')
nx = ny = 10
canvas = np.empty((28*ny, 28*nx))
for i in range(nx):
for j in range(ny):
canvas[(nx-i-1)*28:(nx-i)*28, j*28:(j+1)*28] = figs[i*nx+j]
plt.figure(figsize=(8, 10))
plt.imshow(canvas, origin="upper", cmap="gray")
plt.tight_layout()
if name_fig == None:
path = os.getcwd()+'/out/'
if not os.path.exists(path):
os.makedirs(path)
name_fig = path + str(epoch)+'.png'
plt.savefig(name_fig, bbox_inches='tight')
plt.close('all')
if show:
plt.show()
#%%
tf.reset_default_graph()
bi_dim = 200
b_dim = 2*bi_dim; x_dim = 392
eps = 1e-10
# number of sample b to calculate gen_loss,
# number of sample u to calculate inf_grads
lr=tf.constant(0.0001)
M = tf.placeholder(tf.int32)
x_u = tf.placeholder(tf.float32,[None,x_dim]) #N*d_x
xu_binary = tf.to_float(x_u > .5)
xu_star = tf.tile(tf.expand_dims(xu_binary,axis=1),[1,M,1]) #N*M*d_x
x_l = tf.placeholder(tf.float32,[None,x_dim]) #N*d_x
xl_binary = tf.to_float(x_l > .5)
xl_star = tf.tile(tf.expand_dims(xl_binary,axis=1),[1,M,1]) #N*M*d_x
N = tf.shape(xu_binary)[0]
#encoder q(b|x) = log Ber(b|log_alpha_b)
#logits for bernoulli, p=sigmoid(logits)
log_alpha_b1 = encoder1(xu_star,bi_dim) #N*d_b
q_b1 = Bernoulli(logits=log_alpha_b1) #sample 1 \bv
b_sample1 = q_b1.sample() #M*N*d_b, accompanying with encoder parameter, cannot backprop
b_sample1 = tf.cast(b_sample1,tf.float32) #N*M*d_b
log_alpha_b2 = encoder2(b_sample1 ,bi_dim)
q_b2 = Bernoulli(logits=log_alpha_b2) #sample 1 \bv
b_sample2 = q_b2.sample() #N*d_b, accompanying with encoder parameter, cannot backprop
b_sample2 = tf.cast(b_sample2,tf.float32) #N*M*d_b
#compute decoder p(x|b), gradient of decoder parameter can be automatically given by loss
gen_loss00 = fun(xl_star,b_sample2,reuse_encoder=True,reuse_decoder= False)
gen_loss0 = tf.reduce_mean(gen_loss00,1) #average over M
gen_loss = tf.reduce_mean(gen_loss0) #average over N
gen_opt = tf.train.AdamOptimizer(lr)
gen_vars = tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES, scope='decoder')
gen_gradvars = gen_opt.compute_gradients(gen_loss, var_list=gen_vars)
gen_train_op = gen_opt.apply_gradients(gen_gradvars)
b2_onesample = tf.reshape(tf.slice(b_sample2,[0,0,0],[-1,1,-1]),[-1,bi_dim])
xl_recon_alpha = decoder(b2_onesample,x_dim,reuse=True)
xl_dist = Bernoulli(logits = xl_recon_alpha)
xl_recon = xl_dist.mean()
x_recon = tf.concat([x_u,xl_recon],axis=1)
x_recon = tf.reshape(x_recon,[-1,28,28])
#for M>1, true loss
loss0 = -(tf.reduce_logsumexp(-gen_loss00,axis=1) -tf.log(tf.cast(M,tf.float32)))
loss = tf.reduce_mean(loss0)
#provide encoder q(b|x) gradient by data augmentation
#gradient to log_alpha_b2(phi_2)
u_noise2 = tf.random_uniform(shape=[N,M,bi_dim],maxval=1.0)
P2_1 = tf.sigmoid(-log_alpha_b2)
E2_1 = tf.cast(u_noise2>P2_1,tf.float32)
P2_2 = 1 - P2_1
E2_2 = tf.cast(u_noise2<P2_2,tf.float32)
F2_1 = fun(xl_star,E2_1,reuse_encoder=True,reuse_decoder=True) #N*M
F2_2 = fun(xl_star,E2_2,reuse_encoder=True,reuse_decoder=True)
alpha2_grads = tf.expand_dims(F2_1-F2_2,axis=2)*(u_noise2-0.5) #N*M*d_bi
#alpha2_grads = tf.reduce_mean(alpha2_grads,axis=1)
#gradient to log_alpha_b1(phi_1)
u_noise1 = tf.random_uniform(shape=[N,M,bi_dim],maxval=1.0)
P1_1 = tf.sigmoid(-log_alpha_b1)
E1_1 = tf.cast(u_noise1>P1_1,tf.float32)
P1_2 = 1 - P1_1
E1_2 = tf.cast(u_noise1<P1_2,tf.float32)
log_alpha_b2_1 = encoder2(E1_1 ,bi_dim,reuse=True)
q_b2_1 = Bernoulli(log_alpha_b2_1) #sample 1 \bv
b_sample2_1 = q_b2_1.sample() #N*M*d_bi, accompanying with encoder parameter, cannot backprop
b_sample2_1 = tf.cast(b_sample2_1,tf.float32) #N*M*d_bi
F1_1 = fun(xl_star,b_sample2_1,reuse_encoder=True,reuse_decoder=True) #N*M
log_alpha_b2_2 = encoder2(E1_2 ,bi_dim,reuse=True)
q_b2_2 = Bernoulli(log_alpha_b2_2) #sample 1 \bv
b_sample2_2 = q_b2_2.sample() #N*M*d_bi, accompanying with encoder parameter, cannot backprop
b_sample2_2 = tf.cast(b_sample2_2,tf.float32) #N*M*d_bi
F1_2 = fun(xl_star,b_sample2_2,reuse_encoder=True,reuse_decoder=True) #N*M
alpha1_grads = tf.expand_dims(F1_1-F1_2,axis=2)*(u_noise1-0.5) #N*M*d_bi
inf_opt = tf.train.AdamOptimizer(lr)
log_alpha_b = tf.concat([log_alpha_b1,log_alpha_b2],2)
alpha_grads = tf.concat([alpha1_grads,alpha2_grads],2)
inf_vars = tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES, scope='encoder')
inf_grads = tf.gradients(log_alpha_b, inf_vars, grad_ys=alpha_grads)
inf_gradvars = zip(inf_grads, inf_vars)
inf_train_op = inf_opt.apply_gradients(inf_gradvars)
with tf.control_dependencies([gen_train_op,inf_train_op]):
train_op = tf.no_op()
init_op=tf.global_variables_initializer()
#%% TRAIN
# get data
mnist = input_data.read_data_sets(os.getcwd()+'/MNIST', one_hot=True)
train_data = mnist.train
test_data = mnist.test
valid_data = mnist.validation
directory = os.getcwd()+'/discrete_out/'
if not os.path.exists(directory):
os.makedirs(directory)
batch_size = 100
total_points = mnist.train.num_examples
total_batch = int(total_points / batch_size)
total_test_batch = int(mnist.test.num_examples / batch_size)
total_valid_batch = int(mnist.validation.num_examples / batch_size)
training_epochs = 2000
display_step = total_batch
#%%
def get_loss(sess,data,total_batch,M0):
cost_eval = []
for j in range(total_batch):
xs,_ = data.next_batch(batch_size)
xs_u = xs[:,:392]; xs_l = xs[:,392:]
cost_eval.append(sess.run(loss0,{x_u:xs_u,x_l:xs_l,M:M0}))
return np.mean(cost_eval)
EXPERIMENT = 'SBN_MNIST_Bernoulli_ARM'
print('Training stats....',EXPERIMENT)
sess=tf.InteractiveSession()
sess.run(init_op)
record = []; step = 0
import time
start = time.time()
COUNT=[]; COST=[]; TIME=[];COST_TEST=[];COST_VALID=[];epoch_list=[];time_list=[]
for epoch in range(training_epochs):
avg_cost = 0.
avg_cost_test = 0.
np_lr = 0.0001
for i in range(total_batch):
train_xs,_ = train_data.next_batch(batch_size)
x_upper = train_xs[:,:392]; x_lower = train_xs[:,392:]
#plt.imshow(np.reshape(x_upper[0,:],[14,28]))
_,cost = sess.run([train_op,gen_loss],{x_u:x_upper,x_l:x_lower,lr:np_lr,M:1})
record.append(cost)
step += 1
if epoch%1 == 0:
valid_loss = get_loss(sess,valid_data,total_valid_batch,M0=1)
COUNT.append(step); COST.append(np.mean(record)); TIME.append(time.time()-start)
COST_VALID.append(valid_loss)
print(epoch,'valid_loss=',valid_loss)
if epoch%20 == 0:
test_loss = get_loss(sess,test_data,total_test_batch,M0=1000)
COST_TEST.append(test_loss)
epoch_list.append(epoch)
time_list.append(time.time()-start)
print(epoch,'test_loss=',test_loss)
all_ = [COUNT,COST,TIME,COST_TEST,COST_VALID,epoch_list,time_list]
pickle.dump(all_, open(directory+EXPERIMENT, 'wb'))
#x_re = sess.run(x_recon,{x_u:x_upper,M:1000})
#fig_gnrt(x_re,epoch,bny=0)
record=[]
path = os.getcwd()+'/sbnout/'
if not os.path.exists(path):
os.makedirs(path)
for i in range(20):
x_re = sess.run(x_recon,{x_u:x_upper,M:1})
fig_gnrt(x_re,epoch,bny=1,name_fig=path+'final_'+str(i))
test_loss = get_loss(sess,test_data,total_test_batch,M0=1000)
print(epoch,'test_loss=',test_loss)
print(EXPERIMENT)
| [
"tensorflow.reduce_sum",
"tensorflow.get_collection",
"tensorflow.reset_default_graph",
"numpy.empty",
"tensorflow.reshape",
"matplotlib.pyplot.figure",
"numpy.mean",
"tensorflow.InteractiveSession",
"matplotlib.pyplot.tight_layout",
"tensorflow.nn.relu",
"matplotlib.pyplot.imshow",
"matplotli... | [((225, 246), 'matplotlib.use', 'matplotlib.use', (['"""Agg"""'], {}), "('Agg')\n", (239, 246), False, 'import matplotlib\n'), ((3004, 3028), 'tensorflow.reset_default_graph', 'tf.reset_default_graph', ([], {}), '()\n', (3026, 3028), True, 'import tensorflow as tf\n'), ((3179, 3198), 'tensorflow.constant', 'tf.constant', (['(0.0001)'], {}), '(0.0001)\n', (3190, 3198), True, 'import tensorflow as tf\n'), ((3203, 3227), 'tensorflow.placeholder', 'tf.placeholder', (['tf.int32'], {}), '(tf.int32)\n', (3217, 3227), True, 'import tensorflow as tf\n'), ((3237, 3278), 'tensorflow.placeholder', 'tf.placeholder', (['tf.float32', '[None, x_dim]'], {}), '(tf.float32, [None, x_dim])\n', (3251, 3278), True, 'import tensorflow as tf\n'), ((3296, 3318), 'tensorflow.to_float', 'tf.to_float', (['(x_u > 0.5)'], {}), '(x_u > 0.5)\n', (3307, 3318), True, 'import tensorflow as tf\n'), ((3395, 3436), 'tensorflow.placeholder', 'tf.placeholder', (['tf.float32', '[None, x_dim]'], {}), '(tf.float32, [None, x_dim])\n', (3409, 3436), True, 'import tensorflow as tf\n'), ((3454, 3476), 'tensorflow.to_float', 'tf.to_float', (['(x_l > 0.5)'], {}), '(x_l > 0.5)\n', (3465, 3476), True, 'import tensorflow as tf\n'), ((3858, 3888), 'tensorflow.cast', 'tf.cast', (['b_sample1', 'tf.float32'], {}), '(b_sample1, tf.float32)\n', (3865, 3888), True, 'import tensorflow as tf\n'), ((4093, 4123), 'tensorflow.cast', 'tf.cast', (['b_sample2', 'tf.float32'], {}), '(b_sample2, tf.float32)\n', (4100, 4123), True, 'import tensorflow as tf\n'), ((4311, 4340), 'tensorflow.reduce_mean', 'tf.reduce_mean', (['gen_loss00', '(1)'], {}), '(gen_loss00, 1)\n', (4325, 4340), True, 'import tensorflow as tf\n'), ((4367, 4392), 'tensorflow.reduce_mean', 'tf.reduce_mean', (['gen_loss0'], {}), '(gen_loss0)\n', (4381, 4392), True, 'import tensorflow as tf\n'), ((4419, 4445), 'tensorflow.train.AdamOptimizer', 'tf.train.AdamOptimizer', (['lr'], {}), '(lr)\n', (4441, 4445), True, 'import tensorflow as tf\n'), ((4457, 4522), 'tensorflow.get_collection', 'tf.get_collection', (['tf.GraphKeys.GLOBAL_VARIABLES'], {'scope': '"""decoder"""'}), "(tf.GraphKeys.GLOBAL_VARIABLES, scope='decoder')\n", (4474, 4522), True, 'import tensorflow as tf\n'), ((4861, 4895), 'tensorflow.concat', 'tf.concat', (['[x_u, xl_recon]'], {'axis': '(1)'}), '([x_u, xl_recon], axis=1)\n', (4870, 4895), True, 'import tensorflow as tf\n'), ((4904, 4937), 'tensorflow.reshape', 'tf.reshape', (['x_recon', '[-1, 28, 28]'], {}), '(x_recon, [-1, 28, 28])\n', (4914, 4937), True, 'import tensorflow as tf\n'), ((5045, 5066), 'tensorflow.reduce_mean', 'tf.reduce_mean', (['loss0'], {}), '(loss0)\n', (5059, 5066), True, 'import tensorflow as tf\n'), ((5169, 5220), 'tensorflow.random_uniform', 'tf.random_uniform', ([], {'shape': '[N, M, bi_dim]', 'maxval': '(1.0)'}), '(shape=[N, M, bi_dim], maxval=1.0)\n', (5186, 5220), True, 'import tensorflow as tf\n'), ((5225, 5250), 'tensorflow.sigmoid', 'tf.sigmoid', (['(-log_alpha_b2)'], {}), '(-log_alpha_b2)\n', (5235, 5250), True, 'import tensorflow as tf\n'), ((5258, 5294), 'tensorflow.cast', 'tf.cast', (['(u_noise2 > P2_1)', 'tf.float32'], {}), '(u_noise2 > P2_1, tf.float32)\n', (5265, 5294), True, 'import tensorflow as tf\n'), ((5315, 5351), 'tensorflow.cast', 'tf.cast', (['(u_noise2 < P2_2)', 'tf.float32'], {}), '(u_noise2 < P2_2, tf.float32)\n', (5322, 5351), True, 'import tensorflow as tf\n'), ((5653, 5704), 'tensorflow.random_uniform', 'tf.random_uniform', ([], {'shape': '[N, M, bi_dim]', 'maxval': '(1.0)'}), '(shape=[N, M, bi_dim], maxval=1.0)\n', (5670, 5704), True, 'import tensorflow as tf\n'), ((5709, 5734), 'tensorflow.sigmoid', 'tf.sigmoid', (['(-log_alpha_b1)'], {}), '(-log_alpha_b1)\n', (5719, 5734), True, 'import tensorflow as tf\n'), ((5742, 5778), 'tensorflow.cast', 'tf.cast', (['(u_noise1 > P1_1)', 'tf.float32'], {}), '(u_noise1 > P1_1, tf.float32)\n', (5749, 5778), True, 'import tensorflow as tf\n'), ((5799, 5835), 'tensorflow.cast', 'tf.cast', (['(u_noise1 < P1_2)', 'tf.float32'], {}), '(u_noise1 < P1_2, tf.float32)\n', (5806, 5835), True, 'import tensorflow as tf\n'), ((6043, 6075), 'tensorflow.cast', 'tf.cast', (['b_sample2_1', 'tf.float32'], {}), '(b_sample2_1, tf.float32)\n', (6050, 6075), True, 'import tensorflow as tf\n'), ((6370, 6402), 'tensorflow.cast', 'tf.cast', (['b_sample2_2', 'tf.float32'], {}), '(b_sample2_2, tf.float32)\n', (6377, 6402), True, 'import tensorflow as tf\n'), ((6575, 6601), 'tensorflow.train.AdamOptimizer', 'tf.train.AdamOptimizer', (['lr'], {}), '(lr)\n', (6597, 6601), True, 'import tensorflow as tf\n'), ((6616, 6658), 'tensorflow.concat', 'tf.concat', (['[log_alpha_b1, log_alpha_b2]', '(2)'], {}), '([log_alpha_b1, log_alpha_b2], 2)\n', (6625, 6658), True, 'import tensorflow as tf\n'), ((6671, 6713), 'tensorflow.concat', 'tf.concat', (['[alpha1_grads, alpha2_grads]', '(2)'], {}), '([alpha1_grads, alpha2_grads], 2)\n', (6680, 6713), True, 'import tensorflow as tf\n'), ((6723, 6788), 'tensorflow.get_collection', 'tf.get_collection', (['tf.GraphKeys.GLOBAL_VARIABLES'], {'scope': '"""encoder"""'}), "(tf.GraphKeys.GLOBAL_VARIABLES, scope='encoder')\n", (6740, 6788), True, 'import tensorflow as tf\n'), ((6801, 6857), 'tensorflow.gradients', 'tf.gradients', (['log_alpha_b', 'inf_vars'], {'grad_ys': 'alpha_grads'}), '(log_alpha_b, inf_vars, grad_ys=alpha_grads)\n', (6813, 6857), True, 'import tensorflow as tf\n'), ((7052, 7085), 'tensorflow.global_variables_initializer', 'tf.global_variables_initializer', ([], {}), '()\n', (7083, 7085), True, 'import tensorflow as tf\n'), ((8029, 8052), 'tensorflow.InteractiveSession', 'tf.InteractiveSession', ([], {}), '()\n', (8050, 8052), True, 'import tensorflow as tf\n'), ((8114, 8125), 'time.time', 'time.time', ([], {}), '()\n', (8123, 8125), False, 'import time\n'), ((2093, 2139), 'tensorflow.reduce_sum', 'tf.reduce_sum', (['log_p_x_given_b2'], {'axis': 'axis_dim'}), '(log_p_x_given_b2, axis=axis_dim)\n', (2106, 2139), True, 'import tensorflow as tf\n'), ((2282, 2330), 'seaborn.set_style', 'sns.set_style', (['"""whitegrid"""', "{'axes.grid': False}"], {}), "('whitegrid', {'axes.grid': False})\n", (2295, 2330), True, 'import seaborn as sns\n'), ((2336, 2346), 'matplotlib.pyplot.ioff', 'plt.ioff', ([], {}), '()\n', (2344, 2346), True, 'from matplotlib import pyplot as plt\n'), ((2450, 2478), 'numpy.empty', 'np.empty', (['(28 * ny, 28 * nx)'], {}), '((28 * ny, 28 * nx))\n', (2458, 2478), True, 'import numpy as np\n'), ((2608, 2635), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(8, 10)'}), '(figsize=(8, 10))\n', (2618, 2635), True, 'from matplotlib import pyplot as plt\n'), ((2648, 2695), 'matplotlib.pyplot.imshow', 'plt.imshow', (['canvas'], {'origin': '"""upper"""', 'cmap': '"""gray"""'}), "(canvas, origin='upper', cmap='gray')\n", (2658, 2695), True, 'from matplotlib import pyplot as plt\n'), ((2700, 2718), 'matplotlib.pyplot.tight_layout', 'plt.tight_layout', ([], {}), '()\n', (2716, 2718), True, 'from matplotlib import pyplot as plt\n'), ((2894, 2936), 'matplotlib.pyplot.savefig', 'plt.savefig', (['name_fig'], {'bbox_inches': '"""tight"""'}), "(name_fig, bbox_inches='tight')\n", (2905, 2936), True, 'from matplotlib import pyplot as plt\n'), ((2942, 2958), 'matplotlib.pyplot.close', 'plt.close', (['"""all"""'], {}), "('all')\n", (2951, 2958), True, 'from matplotlib import pyplot as plt\n'), ((3336, 3369), 'tensorflow.expand_dims', 'tf.expand_dims', (['xu_binary'], {'axis': '(1)'}), '(xu_binary, axis=1)\n', (3350, 3369), True, 'import tensorflow as tf\n'), ((3494, 3527), 'tensorflow.expand_dims', 'tf.expand_dims', (['xl_binary'], {'axis': '(1)'}), '(xl_binary, axis=1)\n', (3508, 3527), True, 'import tensorflow as tf\n'), ((3550, 3569), 'tensorflow.shape', 'tf.shape', (['xu_binary'], {}), '(xu_binary)\n', (3558, 3569), True, 'import tensorflow as tf\n'), ((4673, 4716), 'tensorflow.slice', 'tf.slice', (['b_sample2', '[0, 0, 0]', '[-1, 1, -1]'], {}), '(b_sample2, [0, 0, 0], [-1, 1, -1])\n', (4681, 4716), True, 'import tensorflow as tf\n'), ((5496, 5531), 'tensorflow.expand_dims', 'tf.expand_dims', (['(F2_1 - F2_2)'], {'axis': '(2)'}), '(F2_1 - F2_2, axis=2)\n', (5510, 5531), True, 'import tensorflow as tf\n'), ((6503, 6538), 'tensorflow.expand_dims', 'tf.expand_dims', (['(F1_1 - F1_2)'], {'axis': '(2)'}), '(F1_1 - F1_2, axis=2)\n', (6517, 6538), True, 'import tensorflow as tf\n'), ((6959, 7012), 'tensorflow.control_dependencies', 'tf.control_dependencies', (['[gen_train_op, inf_train_op]'], {}), '([gen_train_op, inf_train_op])\n', (6982, 7012), True, 'import tensorflow as tf\n'), ((7028, 7038), 'tensorflow.no_op', 'tf.no_op', ([], {}), '()\n', (7036, 7038), True, 'import tensorflow as tf\n'), ((7269, 7280), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (7278, 7280), False, 'import os\n'), ((7305, 7330), 'os.path.exists', 'os.path.exists', (['directory'], {}), '(directory)\n', (7319, 7330), False, 'import os\n'), ((7336, 7358), 'os.makedirs', 'os.makedirs', (['directory'], {}), '(directory)\n', (7347, 7358), False, 'import os\n'), ((7924, 7942), 'numpy.mean', 'np.mean', (['cost_eval'], {}), '(cost_eval)\n', (7931, 7942), True, 'import numpy as np\n'), ((9416, 9427), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (9425, 9427), False, 'import os\n'), ((9446, 9466), 'os.path.exists', 'os.path.exists', (['path'], {}), '(path)\n', (9460, 9466), False, 'import os\n'), ((9472, 9489), 'os.makedirs', 'os.makedirs', (['path'], {}), '(path)\n', (9483, 9489), False, 'import os\n'), ((774, 787), 'tensorflow.nn.relu', 'tf.nn.relu', (['x'], {}), '(x)\n', (784, 787), True, 'import tensorflow as tf\n'), ((903, 931), 'tensorflow.variable_scope', 'tf.variable_scope', (['"""encoder"""'], {}), "('encoder')\n", (920, 931), True, 'import tensorflow as tf\n'), ((1017, 1069), 'tensorflow.layers.dense', 'tf.layers.dense', (['(x * 2 - 1)', 'bi_dim'], {'name': '"""encoder_1"""'}), "(x * 2 - 1, bi_dim, name='encoder_1')\n", (1032, 1069), True, 'import tensorflow as tf\n'), ((1177, 1205), 'tensorflow.variable_scope', 'tf.variable_scope', (['"""encoder"""'], {}), "('encoder')\n", (1194, 1205), True, 'import tensorflow as tf\n'), ((1291, 1344), 'tensorflow.layers.dense', 'tf.layers.dense', (['(b1 * 2 - 1)', 'bi_dim'], {'name': '"""encoder_3"""'}), "(b1 * 2 - 1, bi_dim, name='encoder_3')\n", (1306, 1344), True, 'import tensorflow as tf\n'), ((1427, 1455), 'tensorflow.variable_scope', 'tf.variable_scope', (['"""decoder"""'], {}), "('decoder')\n", (1444, 1455), True, 'import tensorflow as tf\n'), ((1541, 1599), 'tensorflow.layers.dense', 'tf.layers.dense', (['(b2 * 2 - 1)', 'x_dim', 'None'], {'name': '"""decoder_1"""'}), "(b2 * 2 - 1, x_dim, None, name='decoder_1')\n", (1556, 1599), True, 'import tensorflow as tf\n'), ((2980, 2990), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (2988, 2990), True, 'from matplotlib import pyplot as plt\n'), ((4966, 5006), 'tensorflow.reduce_logsumexp', 'tf.reduce_logsumexp', (['(-gen_loss00)'], {'axis': '(1)'}), '(-gen_loss00, axis=1)\n', (4985, 5006), True, 'import tensorflow as tf\n'), ((7142, 7153), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (7151, 7153), False, 'import os\n'), ((798, 812), 'tensorflow.nn.relu', 'tf.nn.relu', (['(-x)'], {}), '(-x)\n', (808, 812), True, 'import tensorflow as tf\n'), ((2759, 2770), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (2768, 2770), False, 'import os\n'), ((2794, 2814), 'os.path.exists', 'os.path.exists', (['path'], {}), '(path)\n', (2808, 2814), False, 'import os\n'), ((2828, 2845), 'os.makedirs', 'os.makedirs', (['path'], {}), '(path)\n', (2839, 2845), False, 'import os\n'), ((5014, 5036), 'tensorflow.cast', 'tf.cast', (['M', 'tf.float32'], {}), '(M, tf.float32)\n', (5021, 5036), True, 'import tensorflow as tf\n'), ((8775, 8790), 'numpy.mean', 'np.mean', (['record'], {}), '(record)\n', (8782, 8790), True, 'import numpy as np\n'), ((657, 683), 'tensorflow.nn.softplus', 'tf.nn.softplus', (['(-log_alpha)'], {}), '(-log_alpha)\n', (671, 683), True, 'import tensorflow as tf\n'), ((711, 737), 'tensorflow.nn.softplus', 'tf.nn.softplus', (['(-log_alpha)'], {}), '(-log_alpha)\n', (725, 737), True, 'import tensorflow as tf\n'), ((8805, 8816), 'time.time', 'time.time', ([], {}), '()\n', (8814, 8816), False, 'import time\n'), ((9096, 9107), 'time.time', 'time.time', ([], {}), '()\n', (9105, 9107), False, 'import time\n')] |
"""
http://arxiv.org/abs/1412.7449 and https://arxiv.org/abs/1508.04025 (mostly the latter)
TODO: embed start symbol at test time - GET WORKING
read from model path if provided
attention
real prediction/output probabilities isntead of logits
"""
import tensorflow as tf
import numpy as np
class Seq2SeqV3(object):
def __init__(self, config, batch_size, dataset, testing=False, model_path=None):
# configurations
self.src_vocab_size = config.src_vocab_size
self.max_source_len = config.max_source_len
self.embedding_size = config.embedding_size
self.hidden_size = config.hidden_size
self.num_layers = config.num_layers
self.target_vocab_size = config.target_vocab_size
# args
self.dataset = dataset
self.batch_size = batch_size
self.testing = testing
# placeholders
self.learning_rate = tf.placeholder(tf.int32, shape=(), name="lr")
self.source = tf.placeholder(tf.int32, [self.batch_size, self.max_source_len], name="source")
self.source_len = tf.placeholder(tf.int32, [self.batch_size], name="source_len")
self.target = tf.placeholder(tf.int32, [self.batch_size, self.max_source_len], name="target")
self.target_len = tf.placeholder(tf.int32, [self.batch_size], name="target_len")
self.dropout = tf.placeholder(tf.float32, name="dropout")
self.global_step = tf.Variable(0, dtype=tf.int32, trainable=False, name='global_step')
# get word vectors for the source and target
source_embedded, target_embedded = self.get_embeddings(self.source, self.target)
# run everything through the encoder and decoder
self.decoder_output = self.encode_decode(source=source_embedded,
source_len=self.source_len,
target=target_embedded,
target_len=self.target_len)
# compute average per-word loss across all batches (log perplexity)
self.loss = self.cross_entropy_sequence_loss(logits=self.decoder_output,
targets=self.target,
seq_len=self.target_len)
# compute and apply gradients
self.train_step = self.backward_pass(self.loss)
# tf boilerplate
self.check = tf.add_check_numerics_ops()
self.sess = tf.Session()
self.sess.run(tf.global_variables_initializer())
# self.writer = tf.summary.FileWriter('./graphs', self.sess.graph)
# self.writer.close()
def get_embeddings(self, source, target):
source_embedding = tf.get_variable('source_embeddings',
shape=[self.src_vocab_size, self.embedding_size])
source_embedded = tf.nn.embedding_lookup(source_embedding, source)
self.target_embedding = tf.get_variable('target_embeddings',
shape=[self.target_vocab_size, self.embedding_size])
target_embedded = tf.nn.embedding_lookup(self.target_embedding, target)
return source_embedded, target_embedded
def get_source_embeddings(self, source):
""" source: [batch size, max length] = source-side one-hot vectors
target: [batch size, max length] = target-side one-hot vectors
returns word embeddings for each item in the source/target sequence
"""
source_embedding = tf.get_variable('source_embeddings',
shape=[self.src_vocab_size, self.embedding_size])
source_embedded = tf.nn.embedding_lookup(source_embedding, source)
return source_embedded
def get_target_embeddings(self, target):
"""target: [batch size, max length] = target-side one-hot vectors
returns word embeddings for each item in the target sequence
"""
# make instance variable so that decoder can access during test time
self.target_embedding = tf.get_variable('target_embeddings',
shape=[self.target_vocab_size, self.embedding_size])
target_embedded = tf.nn.embedding_lookup(self.target_embedding, target)
return target_embedded
def train_on_batch(self, x_batch, x_lens, y_batch, y_lens, learning_rate=1.0):
""" train on a minibatch of data. x and y are assumed to be
padded to length max_seq_len, with [x/y]_lens reflecting
the original lengths of each sequence
"""
_, logits, loss = self.sess.run([self.train_step, self.decoder_output, self.loss],
feed_dict={
self.source: x_batch,
self.source_len: x_lens,
self.target: y_batch,
self.target_len: y_lens,
self.dropout: 0.5,
self.learning_rate: learning_rate
})
return np.argmax(logits, axis=2), loss
def predict_on_batch(self, x_batch, x_lens, learning_rate=1.0):
""" predict translation for a batch of inputs
TODO - only take x_batch, and feed in the start symbol instead of
the first word from y (which is start symbol)
"""
assert self.testing, 'ERROR: model must be in test mode to make predictions!'
logits = self.sess.run(self.decoder_output, feed_dict={
self.source: x_batch,
self.source_len: x_lens,
self.dropout: 0.5,
self.learning_rate: learning_rate
})
return np.argmax(logits, axis=2), logits
def backward_pass(self, loss):
""" use the given loss to construct a training step
NOTE: Using SGD instead of adagrad or adam because those don't seem to work
"""
train_step = tf.contrib.layers.optimize_loss(self.loss, None,
self.learning_rate, "SGD", clip_gradients=5.0)
return train_step
def cross_entropy_sequence_loss(self, logits, targets, seq_len):
""" logits: [batch size, sequence len, vocab size]
targets: [batch size, sequence len]
lengths: [batch size] = length of each target sequence before padding
computes and returns per-timestep cross-entropy, then averages across sequences and batches
"""
targets = targets[:, 1:] # shift targest forward by 1: ignore start symbol
logits = logits[:, :-1, :] # take off last group of logits so dimensions match up
seq_len = seq_len - 1 # update sequence lengths to reflect this
# cross entropy
losses = tf.nn.sparse_softmax_cross_entropy_with_logits(
logits=logits,
labels=targets)
# Mask out the losses we don't care about
loss_mask = tf.sequence_mask(seq_len, targets.get_shape()[1], dtype=tf.float32)
losses = losses * loss_mask
# get mean log perplexity across all batches
loss = tf.reduce_sum(losses) / tf.to_float(tf.reduce_sum(seq_len))
return loss
def encode_decode(self, source, source_len, target, target_len):
""" source: [batch size, sequence len]
source_len: [batch size] = pre-padding lengths of source sequences
target: [batch size, sequence len]
target_len: [batch size] = pre-padding lengths of targets
runs the source through an encoder, then runs decoder on final hidden state
"""
with tf.variable_scope('encoder'):
encoder_cell = self.build_rnn_cell()
encoder_output = self.run_encoder(source, source_len, encoder_cell)
with tf.variable_scope('decoder'):
decoder_cell = self.build_rnn_cell()
decoder_output = self.run_decoder(target,
target_len,
decoder_cell,
encoder_output['final_state'])
return decoder_output
def run_decoder(self, target, target_len, decoder, initial_state):
""" target: [batch size, sequence len]
target_len: [batch_size] = pre-padded target lengths
decoder: RNNCell
initial_state: tuple([batch size, hidden state size] * batch size )
runs a decoder on target and returns its predictions at each timestep
"""
# TODO - MAKE TARGETS OPTIONAL, UNROLL FOR TARGET MAXLEN
# projection to rnn space
target_proj_W = tf.get_variable("t_proj_W",
shape=[self.embedding_size, self.hidden_size],
initializer=tf.contrib.layers.xavier_initializer())
target_proj_b = tf.get_variable("t_proj_b", shape=[self.hidden_size],
initializer=tf.contrib.layers.xavier_initializer())
# projection to output embeddings
out_embed_W = tf.get_variable("o_embed_W",
shape=[self.hidden_size, self.embedding_size],
initializer=tf.contrib.layers.xavier_initializer())
out_embed_b = tf.get_variable("o_embed_b",
shape=[self.embedding_size],
initializer=tf.contrib.layers.xavier_initializer())
# projection to logits
out_W = tf.get_variable("Wo", shape=[self.embedding_size, self.target_vocab_size],
initializer=tf.contrib.layers.xavier_initializer())
out_b = tf.get_variable("bo", shape=[self.target_vocab_size],
initializer=tf.contrib.layers.xavier_initializer())
# decode source by initializing with encoder's final hidden state
target_x = tf.unstack(target, axis=1) # break the target into a list of word vectors
s = initial_state # intial state = encoder's final state
logits = []
for t in range(self.max_source_len):
if t > 0: tf.get_variable_scope().reuse_variables() # reuse variables after 1st iteration
if self.testing and t == 0: # at test time, kick things off w/start token
_, start_tok = self.dataset.get_start_token_indices() # get start token index for decoding lang
start_vec = np.full([self.batch_size], start_tok)
x = tf.nn.embedding_lookup(self.target_embedding, start_vec) # look up start token
elif not self.testing:
x = target_x[t] # while training, feed in correct input
projection = tf.matmul(x, target_proj_W) + target_proj_b # project embedding into rnn space
h, s = decoder(projection, s) # s is last encoder state when t == 0
out_embedding = tf.matmul(h, out_embed_W) + out_embed_b # project output to target embedding space
logit = tf.matmul(out_embedding, out_W) + out_b
logits.append(logit)
if self.testing:
prob = tf.nn.softmax(logit)
x = tf.cast(tf.argmax(prob, 1), tf.int32) # if testing, use cur pred as next input
x = tf.nn.embedding_lookup(self.target_embedding, x)
logits = tf.stack(logits)
logits = tf.transpose(logits, [1, 0, 2]) # get into [batch size, sequence len, vocab size]
return logits
def run_encoder(self, source, source_len, cell):
""" source: [batch size, seq len]
source_len: [batch size] = pre-padding lengths
cell: RNNCell
runs the cell inputs for source-len timesteps
"""
outputs, state = tf.nn.dynamic_rnn(
cell=cell,
inputs=source,
sequence_length=source_len,
dtype=tf.float32)
return {'outputs': outputs, 'final_state': state}
def build_rnn_cell(self):
""" builds a stacked RNNCell according to specs defined in the model's config
"""
cell = tf.nn.rnn_cell.BasicLSTMCell(self.hidden_size, state_is_tuple=True)
cell = tf.nn.rnn_cell.DropoutWrapper(cell,
input_keep_prob=self.dropout,
output_keep_prob=self.dropout)
stacked_cell = tf.nn.rnn_cell.MultiRNNCell([cell]*self.num_layers, state_is_tuple=True)
return stacked_cell
| [
"tensorflow.contrib.layers.xavier_initializer",
"tensorflow.reduce_sum",
"tensorflow.add_check_numerics_ops",
"numpy.argmax",
"tensorflow.get_variable_scope",
"tensorflow.nn.rnn_cell.DropoutWrapper",
"tensorflow.matmul",
"tensorflow.Variable",
"tensorflow.get_variable",
"numpy.full",
"tensorflow... | [((997, 1042), 'tensorflow.placeholder', 'tf.placeholder', (['tf.int32'], {'shape': '()', 'name': '"""lr"""'}), "(tf.int32, shape=(), name='lr')\n", (1011, 1042), True, 'import tensorflow as tf\n'), ((1069, 1148), 'tensorflow.placeholder', 'tf.placeholder', (['tf.int32', '[self.batch_size, self.max_source_len]'], {'name': '"""source"""'}), "(tf.int32, [self.batch_size, self.max_source_len], name='source')\n", (1083, 1148), True, 'import tensorflow as tf\n'), ((1175, 1237), 'tensorflow.placeholder', 'tf.placeholder', (['tf.int32', '[self.batch_size]'], {'name': '"""source_len"""'}), "(tf.int32, [self.batch_size], name='source_len')\n", (1189, 1237), True, 'import tensorflow as tf\n'), ((1264, 1343), 'tensorflow.placeholder', 'tf.placeholder', (['tf.int32', '[self.batch_size, self.max_source_len]'], {'name': '"""target"""'}), "(tf.int32, [self.batch_size, self.max_source_len], name='target')\n", (1278, 1343), True, 'import tensorflow as tf\n'), ((1370, 1432), 'tensorflow.placeholder', 'tf.placeholder', (['tf.int32', '[self.batch_size]'], {'name': '"""target_len"""'}), "(tf.int32, [self.batch_size], name='target_len')\n", (1384, 1432), True, 'import tensorflow as tf\n'), ((1459, 1501), 'tensorflow.placeholder', 'tf.placeholder', (['tf.float32'], {'name': '"""dropout"""'}), "(tf.float32, name='dropout')\n", (1473, 1501), True, 'import tensorflow as tf\n'), ((1529, 1596), 'tensorflow.Variable', 'tf.Variable', (['(0)'], {'dtype': 'tf.int32', 'trainable': '(False)', 'name': '"""global_step"""'}), "(0, dtype=tf.int32, trainable=False, name='global_step')\n", (1540, 1596), True, 'import tensorflow as tf\n'), ((2540, 2567), 'tensorflow.add_check_numerics_ops', 'tf.add_check_numerics_ops', ([], {}), '()\n', (2565, 2567), True, 'import tensorflow as tf\n'), ((2588, 2600), 'tensorflow.Session', 'tf.Session', ([], {}), '()\n', (2598, 2600), True, 'import tensorflow as tf\n'), ((2835, 2926), 'tensorflow.get_variable', 'tf.get_variable', (['"""source_embeddings"""'], {'shape': '[self.src_vocab_size, self.embedding_size]'}), "('source_embeddings', shape=[self.src_vocab_size, self.\n embedding_size])\n", (2850, 2926), True, 'import tensorflow as tf\n'), ((2991, 3039), 'tensorflow.nn.embedding_lookup', 'tf.nn.embedding_lookup', (['source_embedding', 'source'], {}), '(source_embedding, source)\n', (3013, 3039), True, 'import tensorflow as tf\n'), ((3072, 3166), 'tensorflow.get_variable', 'tf.get_variable', (['"""target_embeddings"""'], {'shape': '[self.target_vocab_size, self.embedding_size]'}), "('target_embeddings', shape=[self.target_vocab_size, self.\n embedding_size])\n", (3087, 3166), True, 'import tensorflow as tf\n'), ((3237, 3290), 'tensorflow.nn.embedding_lookup', 'tf.nn.embedding_lookup', (['self.target_embedding', 'target'], {}), '(self.target_embedding, target)\n', (3259, 3290), True, 'import tensorflow as tf\n'), ((3666, 3757), 'tensorflow.get_variable', 'tf.get_variable', (['"""source_embeddings"""'], {'shape': '[self.src_vocab_size, self.embedding_size]'}), "('source_embeddings', shape=[self.src_vocab_size, self.\n embedding_size])\n", (3681, 3757), True, 'import tensorflow as tf\n'), ((3822, 3870), 'tensorflow.nn.embedding_lookup', 'tf.nn.embedding_lookup', (['source_embedding', 'source'], {}), '(source_embedding, source)\n', (3844, 3870), True, 'import tensorflow as tf\n'), ((4220, 4314), 'tensorflow.get_variable', 'tf.get_variable', (['"""target_embeddings"""'], {'shape': '[self.target_vocab_size, self.embedding_size]'}), "('target_embeddings', shape=[self.target_vocab_size, self.\n embedding_size])\n", (4235, 4314), True, 'import tensorflow as tf\n'), ((4385, 4438), 'tensorflow.nn.embedding_lookup', 'tf.nn.embedding_lookup', (['self.target_embedding', 'target'], {}), '(self.target_embedding, target)\n', (4407, 4438), True, 'import tensorflow as tf\n'), ((6317, 6416), 'tensorflow.contrib.layers.optimize_loss', 'tf.contrib.layers.optimize_loss', (['self.loss', 'None', 'self.learning_rate', '"""SGD"""'], {'clip_gradients': '(5.0)'}), "(self.loss, None, self.learning_rate, 'SGD',\n clip_gradients=5.0)\n", (6348, 6416), True, 'import tensorflow as tf\n'), ((7175, 7252), 'tensorflow.nn.sparse_softmax_cross_entropy_with_logits', 'tf.nn.sparse_softmax_cross_entropy_with_logits', ([], {'logits': 'logits', 'labels': 'targets'}), '(logits=logits, labels=targets)\n', (7221, 7252), True, 'import tensorflow as tf\n'), ((10415, 10441), 'tensorflow.unstack', 'tf.unstack', (['target'], {'axis': '(1)'}), '(target, axis=1)\n', (10425, 10441), True, 'import tensorflow as tf\n'), ((12033, 12049), 'tensorflow.stack', 'tf.stack', (['logits'], {}), '(logits)\n', (12041, 12049), True, 'import tensorflow as tf\n'), ((12067, 12098), 'tensorflow.transpose', 'tf.transpose', (['logits', '[1, 0, 2]'], {}), '(logits, [1, 0, 2])\n', (12079, 12098), True, 'import tensorflow as tf\n'), ((12471, 12564), 'tensorflow.nn.dynamic_rnn', 'tf.nn.dynamic_rnn', ([], {'cell': 'cell', 'inputs': 'source', 'sequence_length': 'source_len', 'dtype': 'tf.float32'}), '(cell=cell, inputs=source, sequence_length=source_len,\n dtype=tf.float32)\n', (12488, 12564), True, 'import tensorflow as tf\n'), ((12813, 12880), 'tensorflow.nn.rnn_cell.BasicLSTMCell', 'tf.nn.rnn_cell.BasicLSTMCell', (['self.hidden_size'], {'state_is_tuple': '(True)'}), '(self.hidden_size, state_is_tuple=True)\n', (12841, 12880), True, 'import tensorflow as tf\n'), ((12896, 12996), 'tensorflow.nn.rnn_cell.DropoutWrapper', 'tf.nn.rnn_cell.DropoutWrapper', (['cell'], {'input_keep_prob': 'self.dropout', 'output_keep_prob': 'self.dropout'}), '(cell, input_keep_prob=self.dropout,\n output_keep_prob=self.dropout)\n', (12925, 12996), True, 'import tensorflow as tf\n'), ((13107, 13181), 'tensorflow.nn.rnn_cell.MultiRNNCell', 'tf.nn.rnn_cell.MultiRNNCell', (['([cell] * self.num_layers)'], {'state_is_tuple': '(True)'}), '([cell] * self.num_layers, state_is_tuple=True)\n', (13134, 13181), True, 'import tensorflow as tf\n'), ((2623, 2656), 'tensorflow.global_variables_initializer', 'tf.global_variables_initializer', ([], {}), '()\n', (2654, 2656), True, 'import tensorflow as tf\n'), ((5305, 5330), 'numpy.argmax', 'np.argmax', (['logits'], {'axis': '(2)'}), '(logits, axis=2)\n', (5314, 5330), True, 'import numpy as np\n'), ((6064, 6089), 'numpy.argmax', 'np.argmax', (['logits'], {'axis': '(2)'}), '(logits, axis=2)\n', (6073, 6089), True, 'import numpy as np\n'), ((7522, 7543), 'tensorflow.reduce_sum', 'tf.reduce_sum', (['losses'], {}), '(losses)\n', (7535, 7543), True, 'import tensorflow as tf\n'), ((8048, 8076), 'tensorflow.variable_scope', 'tf.variable_scope', (['"""encoder"""'], {}), "('encoder')\n", (8065, 8076), True, 'import tensorflow as tf\n'), ((8229, 8257), 'tensorflow.variable_scope', 'tf.variable_scope', (['"""decoder"""'], {}), "('decoder')\n", (8246, 8257), True, 'import tensorflow as tf\n'), ((7558, 7580), 'tensorflow.reduce_sum', 'tf.reduce_sum', (['seq_len'], {}), '(seq_len)\n', (7571, 7580), True, 'import tensorflow as tf\n'), ((9274, 9312), 'tensorflow.contrib.layers.xavier_initializer', 'tf.contrib.layers.xavier_initializer', ([], {}), '()\n', (9310, 9312), True, 'import tensorflow as tf\n'), ((9444, 9482), 'tensorflow.contrib.layers.xavier_initializer', 'tf.contrib.layers.xavier_initializer', ([], {}), '()\n', (9480, 9482), True, 'import tensorflow as tf\n'), ((9712, 9750), 'tensorflow.contrib.layers.xavier_initializer', 'tf.contrib.layers.xavier_initializer', ([], {}), '()\n', (9748, 9750), True, 'import tensorflow as tf\n'), ((9920, 9958), 'tensorflow.contrib.layers.xavier_initializer', 'tf.contrib.layers.xavier_initializer', ([], {}), '()\n', (9956, 9958), True, 'import tensorflow as tf\n'), ((10126, 10164), 'tensorflow.contrib.layers.xavier_initializer', 'tf.contrib.layers.xavier_initializer', ([], {}), '()\n', (10162, 10164), True, 'import tensorflow as tf\n'), ((10280, 10318), 'tensorflow.contrib.layers.xavier_initializer', 'tf.contrib.layers.xavier_initializer', ([], {}), '()\n', (10316, 10318), True, 'import tensorflow as tf\n'), ((11048, 11085), 'numpy.full', 'np.full', (['[self.batch_size]', 'start_tok'], {}), '([self.batch_size], start_tok)\n', (11055, 11085), True, 'import numpy as np\n'), ((11106, 11162), 'tensorflow.nn.embedding_lookup', 'tf.nn.embedding_lookup', (['self.target_embedding', 'start_vec'], {}), '(self.target_embedding, start_vec)\n', (11128, 11162), True, 'import tensorflow as tf\n'), ((11357, 11384), 'tensorflow.matmul', 'tf.matmul', (['x', 'target_proj_W'], {}), '(x, target_proj_W)\n', (11366, 11384), True, 'import tensorflow as tf\n'), ((11584, 11609), 'tensorflow.matmul', 'tf.matmul', (['h', 'out_embed_W'], {}), '(h, out_embed_W)\n', (11593, 11609), True, 'import tensorflow as tf\n'), ((11688, 11719), 'tensorflow.matmul', 'tf.matmul', (['out_embedding', 'out_W'], {}), '(out_embedding, out_W)\n', (11697, 11719), True, 'import tensorflow as tf\n'), ((11815, 11835), 'tensorflow.nn.softmax', 'tf.nn.softmax', (['logit'], {}), '(logit)\n', (11828, 11835), True, 'import tensorflow as tf\n'), ((11966, 12014), 'tensorflow.nn.embedding_lookup', 'tf.nn.embedding_lookup', (['self.target_embedding', 'x'], {}), '(self.target_embedding, x)\n', (11988, 12014), True, 'import tensorflow as tf\n'), ((11864, 11882), 'tensorflow.argmax', 'tf.argmax', (['prob', '(1)'], {}), '(prob, 1)\n', (11873, 11882), True, 'import tensorflow as tf\n'), ((10707, 10730), 'tensorflow.get_variable_scope', 'tf.get_variable_scope', ([], {}), '()\n', (10728, 10730), True, 'import tensorflow as tf\n')] |
import numpy as np
import pandas as pd
import scipy.sparse as sp
import matchzoo
import collections
from setting_keywords import KeyWordSettings
from handlers.output_handler import FileHandler
def _laplacian_normalize(adj):
"""Symmetrically normalize adjacency matrix."""
adj = sp.coo_matrix(adj)
rowsum = np.array(adj.sum(1))
d_inv_sqrt = np.power(rowsum, -0.5).flatten()
d_inv_sqrt[np.isinf(d_inv_sqrt)] = 0.
d_mat_inv_sqrt = sp.diags(d_inv_sqrt)
return (adj.dot(d_mat_inv_sqrt).transpose().dot(d_mat_inv_sqrt)).A
class MatchInteraction(object):
"""
Interactions object. Contains (at a minimum) pair of user-item
interactions, but can also be enriched with ratings, timestamps,
and interaction weights.
For *implicit feedback* scenarios, user ids and item ids should
only be provided for user-item pairs where an interaction was
observed. All pairs that are not provided are treated as missing
observations, and often interpreted as (implicit) negative
signals.
For *explicit feedback* scenarios, user ids, item ids, and
ratings should be provided for all user-item-rating triplets
that were observed in the dataset.
This class is designed specificlaly for matching models only. Since I don't want
to use MatchZoo datapack at all.
Parameters
----------
data_pack:
Attributes
----------
unique_query_ids: `np.ndarray`array of np.int32
array of user ids of the user-item pairs
query_contents: array of np.int32
array of item ids of the user-item pairs
query_lengths: array of np.float32, optional
array of ratings
unique_doc_ids: array of np.int32, optional
array of timestamps
doc_contents: array of np.float32, optional
array of weights
doc_lengths: int, optional
Number of distinct users in the dataset.
pos_queries: list[int]
Number of distinct items in the dataset.
pos_docs: list[int]
Number of distinct items in the dataset.
negatives: dict
"""
def __init__(self, data_pack: matchzoo.DataPack, **kargs):
# Note that, these indices are not from 0.
FileHandler.myprint("Converting DataFrame to Normal Dictionary of Data")
self.unique_query_ids, \
self.dict_query_contents, \
self.dict_query_lengths, \
self.dict_query_raw_contents, \
self.dict_query_positions = self.convert_leftright(data_pack.left, text_key="text_left",
length_text_key="length_left",
raw_text_key="raw_text_left")
self.data_pack = data_pack
assert len(self.unique_query_ids) == len(set(self.unique_query_ids)), "Must be unique ids"
""" Why do I need to sort it? I have no idea why did I do it? """
self.unique_doc_ids, \
self.dict_doc_contents, \
self.dict_doc_lengths, \
self.dict_doc_raw_contents, \
self.dict_doc_positions = self.convert_leftright(data_pack.right, text_key="text_right",
length_text_key="length_right",
raw_text_key="raw_text_right")
assert len(self.unique_doc_ids) == len(set(self.unique_doc_ids)), "Must be unique ids for doc ids"
assert len(self.unique_query_ids) != len(
self.unique_doc_ids), "Impossible to have equal number of docs and number of original tweets"
self.pos_queries, \
self.pos_docs, \
self.negatives, \
self.unique_queries_test = self.convert_relations(data_pack.relation)
# for queries, padded
self.np_query_contents = np.array([self.dict_query_contents[q] for q in self.pos_queries])
self.np_query_lengths = np.array([self.dict_query_lengths[q] for q in self.pos_queries])
self.query_positions = np.array([self.dict_query_positions[q] for q in self.pos_queries])
# for docs, padded
self.np_doc_contents = np.array([self.dict_doc_contents[d] for d in self.pos_docs])
self.np_doc_lengths = np.array([self.dict_doc_lengths[d] for d in self.pos_docs])
self.doc_positions = np.array([self.dict_doc_positions[d] for d in self.pos_docs])
assert self.np_query_lengths.shape == self.np_doc_lengths.shape
self.padded_doc_length = len(self.np_doc_contents[0])
self.padded_query_length = len(self.np_query_contents[0])
def convert_leftright(self, part: pd.DataFrame, text_key: str, length_text_key: str, raw_text_key: str, **kargs):
""" Converting the dataframe of interactions """
ids, contents_dict, lengths_dict, position_dict = [], {}, {}, {}
raw_content_dict = {}
# Why don't we use the queryID as the key for dictionary????
FileHandler.myprint("[NOTICE] MatchZoo use queryID and docID as index in dataframe left and right, "
"therefore, iterrows will return index which is left_id or right_id")
for index, row in part.iterrows(): # very dangerous, be careful because it may change order!!!
ids.append(index)
text_ = row[text_key] # text_ here is converted to numbers and padded
raw_content_dict[index] = row[raw_text_key]
if length_text_key not in row:
length_ = len(text_)
else:
length_ = row[length_text_key]
assert length_ != 0
assert index not in contents_dict
contents_dict[index] = text_
lengths_dict[index] = length_
position_dict[index] = np.pad(np.arange(length_) + 1, (0, len(text_) - length_), 'constant')
return np.array(ids), contents_dict, lengths_dict, raw_content_dict, position_dict
def convert_relations(self, relation: pd.DataFrame):
""" Convert relations.
We want to retrieve positive interactions and negative interactions. Particularly,
for every pair (query, doc) = 1, we get a list of negatives of the query q
It is possible that a query may have multiple positive docs. Therefore, negatives[q]
may vary the lengths but not too much.
"""
queries, docs, negatives = [], [], collections.defaultdict(list)
unique_queries = collections.defaultdict(list)
for index, row in relation.iterrows():
query = row["id_left"]
doc = row["id_right"]
label = row["label"]
assert label == 0 or label == 1
unique_queries[query] = unique_queries.get(query, [[], [], [], []]) # doc, label, content, length
a, b, c, d = unique_queries[query]
a.append(doc)
b.append(label)
c.append(self.dict_doc_contents[doc])
d.append(self.dict_doc_lengths[doc])
if label == 1:
queries.append(query)
docs.append(doc)
elif label == 0:
negatives[query].append(doc)
assert len(queries) == len(docs)
return np.array(queries), np.array(docs), negatives, unique_queries
def __repr__(self):
return ('<Interactions dataset ({num_users} users x {num_items} items '
'x {num_interactions} interactions)>'
.format(
num_users=self.num_users,
num_items=self.num_items,
num_interactions=len(self)
))
def _check(self):
pass
class BaseClassificationInteractions(object):
""" Base classification interactions for fact-checking with evidences """
def __init__(self, data_pack: matchzoo.DataPack, **kargs):
# FileHandler.myprint("Converting DataFrame to Normal Dictionary of Data")
self.output_handler = kargs[KeyWordSettings.OutputHandlerFactChecking]
self.output_handler.myprint("Converting DataFrame to Normal Dictionary of Data")
additional_field = {KeyWordSettings.FCClass.CharSourceKey: "char_claim_source",
KeyWordSettings.GNN_Window: kargs[KeyWordSettings.GNN_Window]}
self.unique_query_ids, \
self.dict_claim_contents, \
self.dict_claim_lengths, \
self.dict_query_raw_contents, \
self.dict_query_positions, \
self.dict_claim_source, \
self.dict_raw_claim_source, \
self.dict_char_left_src, \
self.dict_query_adj = self.convert_leftright(data_pack.left, text_key="text_left",
length_text_key="length_left", raw_text_key="raw_text_left",
source_key="claim_source", raw_source_key="raw_claim_source",
**additional_field)
self.data_pack = data_pack
assert len(self.unique_query_ids) == len(set(self.unique_query_ids)), "Must be unique ids"
""" Why do I need to sort it? I have no idea why did I do it? """
additional_field = {KeyWordSettings.FCClass.CharSourceKey: "char_evidence_source",
KeyWordSettings.GNN_Window: kargs[KeyWordSettings.GNN_Window]}
self.unique_doc_ids, \
self.dict_doc_contents, \
self.dict_doc_lengths, \
self.dict_doc_raw_contents, \
self.dict_doc_positions, \
self.dict_evd_source, \
self.dict_raw_evd_source, \
self.dict_char_right_src, \
self.dict_doc_adj = self.convert_leftright(data_pack.right, text_key="text_right",
length_text_key="length_right",
raw_text_key="raw_text_right", source_key="evidence_source",
raw_source_key="raw_evidence_source", **additional_field)
assert len(self.unique_doc_ids) == len(set(self.unique_doc_ids)), "Must be unique ids for doc ids"
assert len(self.unique_query_ids) != len(
self.unique_doc_ids), "Impossible to have equal number of docs and number of original tweets"
def convert_leftright(self, part: pd.DataFrame, text_key: str, length_text_key: str, raw_text_key: str,
source_key: str, raw_source_key: str, **kargs):
""" Converting the dataframe of interactions """
ids, contents_dict, lengths_dict, position_dict = [], {}, {}, {}
raw_content_dict, sources, raw_sources, char_sources = {}, {}, {}, {}
dict_adj = {}
fixed_length = 30 if text_key == 'text_left' else 100
char_source_key = kargs[KeyWordSettings.FCClass.CharSourceKey]
# Why don't we use the queryID as the key for dictionary????
self.output_handler.myprint("[NOTICE] MatchZoo use queryID and docID as index in dataframe left and right, "
"therefore, iterrows will return index which is left_id or right_id")
flag = False
for index, row in part.iterrows(): # very dangerous, be careful because it may change order!!!
ids.append(index)
text_ = row[text_key] # text_ here is converted to numbers and padded
raw_content_dict[index] = row[raw_text_key]
if flag is False:
print(text_)
flag=True
if length_text_key not in row:
length_ = len(text_)
else:
length_ = row[length_text_key]
assert length_ != 0
assert index not in contents_dict
contents_dict[index] = text_
lengths_dict[index] = length_
position_dict[index] = np.pad(np.arange(length_) + 1, (0, len(text_) - length_), 'constant')
sources[index] = row[source_key]
raw_sources[index] = row[raw_source_key]
char_sources[index] = row[char_source_key]
# calculate the adj in list type
adj = [[1 if ((i - 2 <= j <= i + 2 or text_[i] == text_[j]) and max(i, j) < length_) else 0
for j in range(fixed_length)] for i in range(fixed_length)]
dict_adj[index] = adj
return np.array(ids), contents_dict, lengths_dict, raw_content_dict, \
position_dict, sources, raw_sources, char_sources, dict_adj
def convert_relations(self, relation: pd.DataFrame):
pass
class ClassificationInteractions(BaseClassificationInteractions):
"""
This class is for classification based on evidences with GAT.
# Modified by: <NAME>. 2021/9/13 14:57
Query - [list of evidences] -> labels
"""
def __init__(self, data_pack: matchzoo.DataPack, **kargs):
super(ClassificationInteractions, self).__init__(data_pack, **kargs)
# (1) unique claims, (2) labels for each claim and (3) info of each claim
self.claims, self.claims_labels, self.dict_claims_and_evidences_test = \
self.convert_relations(data_pack.relation)
# for queries, padded
self.np_query_contents = np.array([self.dict_claim_contents[q] for q in self.claims])
self.np_query_lengths = np.array([self.dict_claim_lengths[q] for q in self.claims])
self.np_query_char_source = np.array([self.dict_char_left_src[q] for q in self.claims])
self.query_positions = np.array([self.dict_query_positions[q] for q in self.claims])
self.np_query_adj = np.array([self.dict_query_adj[q] for q in self.claims]) # query_adj matrix
# assert self.np_query_lengths.shape == self.np_doc_lengths.shape
self.padded_doc_length = len(self.dict_doc_contents[self.unique_doc_ids[0]])
self.padded_doc_char_source_length = len(self.dict_char_right_src[self.unique_doc_ids[0]])
# self.padded_query_length = len(self.np_query_contents[0])
def convert_leftright(self, part: pd.DataFrame, text_key: str, length_text_key: str, raw_text_key: str,
source_key: str, raw_source_key: str, **kargs):
""" Converting the dataframe of interactions
Compress the text & build GAT adjacent matrix
"""
ids, contents_dict, lengths_dict, position_dict = [], {}, {}, {}
raw_content_dict, sources, raw_sources, char_sources = {}, {}, {}, {}
dict_adj = {}
fixed_length = 30 if text_key == 'text_left' else 100
char_source_key = kargs[KeyWordSettings.FCClass.CharSourceKey]
# Why don't we use the queryID as the key for dictionary????
self.output_handler.myprint("[NOTICE] MatchZoo use queryID and docID as index in dataframe left and right, "
"therefore, iterrows will return index which is left_id or right_id")
for index, row in part.iterrows(): # very dangerous, be careful because it may change order!!!
ids.append(index)
text_, adj, length_ = self.convert_text(row[text_key], fixed_length, row[length_text_key],
kargs[KeyWordSettings.GNN_Window])
# if fixed_length==100:
# # contain raw text to lstm
# text_ = row[text_key] # text_ here is converted to numbers and padded
# if length_text_key not in row:
# length_ = len(text_)
# else:
# length_ = row[length_text_key]
raw_content_dict[index] = row[raw_text_key] # origin text
assert length_ != 0
assert index not in contents_dict
contents_dict[index] = text_
lengths_dict[index] = length_
position_dict[index] = np.pad(np.arange(length_) + 1, (0, len(text_) - length_), 'constant')
sources[index] = row[source_key]
raw_sources[index] = row[raw_source_key]
char_sources[index] = row[char_source_key]
dict_adj[index] = adj
return np.array(ids), contents_dict, lengths_dict, raw_content_dict, \
position_dict, sources, raw_sources, char_sources, dict_adj
def convert_text(self, raw_text, fixed_length, length, window_size=5):
words_list = list(set(raw_text[:length])) # remove duplicate words in original order
words_list.sort(key=raw_text.index)
words2id = {word: id for id, word in enumerate(words_list)}
length_ = len(words2id)
neighbours = [set() for _ in range(length_)]
# window_size = window_size if fixed_length == 30 else 300
for i, word in enumerate(raw_text[:length]):
for j in range(max(i-window_size+1, 0), min(i+window_size, length)):
neighbours[words2id[word]].add(words2id[raw_text[j]])
# gat graph
adj = [[1 if (max(i, j) < length_) and (j in neighbours[i]) else 0 for j in range(fixed_length)]
for i in range(fixed_length)]
words_list.extend([0 for _ in range(fixed_length-length_)])
adj = _laplacian_normalize(np.array(adj))
return words_list, adj, length_
def convert_relations(self, relation: pd.DataFrame):
""" Convert relations.
We want to retrieve positive interactions and negative interactions. Particularly,
for every pair (query, doc) = 1, we get a list of negatives of the query q
It is possible that a query may have multiple positive docs. Therefore, negatives[q]
may vary the lengths but not too much.
"""
queries = [] # , collections.defaultdict(list)
queries_labels = []
unique_queries = collections.defaultdict(list)
set_queries = set()
for index, row in relation.iterrows():
query = row["id_left"]
doc = row["id_right"]
label = row["label"]
# assert label == 0 or label == 1
unique_queries[query] = unique_queries.get(query, [[], [], [], [], []]) # doc, label, content, length
a, b, c, d, e = unique_queries[query]
a.append(doc)
b.append(label)
c.append(self.dict_doc_contents[doc])
d.append(self.dict_doc_lengths[doc])
e.append(self.dict_doc_adj[doc])
if query not in set_queries:
queries.append(query) # same as unique_queries
queries_labels.append(label)
set_queries.add(query)
assert len(queries) == len(unique_queries)
return np.array(queries), np.array(queries_labels), unique_queries
| [
"scipy.sparse.diags",
"numpy.power",
"handlers.output_handler.FileHandler.myprint",
"numpy.isinf",
"collections.defaultdict",
"scipy.sparse.coo_matrix",
"numpy.array",
"numpy.arange"
] | [((289, 307), 'scipy.sparse.coo_matrix', 'sp.coo_matrix', (['adj'], {}), '(adj)\n', (302, 307), True, 'import scipy.sparse as sp\n'), ((455, 475), 'scipy.sparse.diags', 'sp.diags', (['d_inv_sqrt'], {}), '(d_inv_sqrt)\n', (463, 475), True, 'import scipy.sparse as sp\n'), ((407, 427), 'numpy.isinf', 'np.isinf', (['d_inv_sqrt'], {}), '(d_inv_sqrt)\n', (415, 427), True, 'import numpy as np\n'), ((2340, 2412), 'handlers.output_handler.FileHandler.myprint', 'FileHandler.myprint', (['"""Converting DataFrame to Normal Dictionary of Data"""'], {}), "('Converting DataFrame to Normal Dictionary of Data')\n", (2359, 2412), False, 'from handlers.output_handler import FileHandler\n'), ((3938, 4003), 'numpy.array', 'np.array', (['[self.dict_query_contents[q] for q in self.pos_queries]'], {}), '([self.dict_query_contents[q] for q in self.pos_queries])\n', (3946, 4003), True, 'import numpy as np\n'), ((4036, 4100), 'numpy.array', 'np.array', (['[self.dict_query_lengths[q] for q in self.pos_queries]'], {}), '([self.dict_query_lengths[q] for q in self.pos_queries])\n', (4044, 4100), True, 'import numpy as np\n'), ((4132, 4198), 'numpy.array', 'np.array', (['[self.dict_query_positions[q] for q in self.pos_queries]'], {}), '([self.dict_query_positions[q] for q in self.pos_queries])\n', (4140, 4198), True, 'import numpy as np\n'), ((4258, 4318), 'numpy.array', 'np.array', (['[self.dict_doc_contents[d] for d in self.pos_docs]'], {}), '([self.dict_doc_contents[d] for d in self.pos_docs])\n', (4266, 4318), True, 'import numpy as np\n'), ((4349, 4408), 'numpy.array', 'np.array', (['[self.dict_doc_lengths[d] for d in self.pos_docs]'], {}), '([self.dict_doc_lengths[d] for d in self.pos_docs])\n', (4357, 4408), True, 'import numpy as np\n'), ((4438, 4499), 'numpy.array', 'np.array', (['[self.dict_doc_positions[d] for d in self.pos_docs]'], {}), '([self.dict_doc_positions[d] for d in self.pos_docs])\n', (4446, 4499), True, 'import numpy as np\n'), ((5057, 5234), 'handlers.output_handler.FileHandler.myprint', 'FileHandler.myprint', (['"""[NOTICE] MatchZoo use queryID and docID as index in dataframe left and right, therefore, iterrows will return index which is left_id or right_id"""'], {}), "(\n '[NOTICE] MatchZoo use queryID and docID as index in dataframe left and right, therefore, iterrows will return index which is left_id or right_id'\n )\n", (5076, 5234), False, 'from handlers.output_handler import FileHandler\n'), ((6547, 6576), 'collections.defaultdict', 'collections.defaultdict', (['list'], {}), '(list)\n', (6570, 6576), False, 'import collections\n'), ((13271, 13331), 'numpy.array', 'np.array', (['[self.dict_claim_contents[q] for q in self.claims]'], {}), '([self.dict_claim_contents[q] for q in self.claims])\n', (13279, 13331), True, 'import numpy as np\n'), ((13364, 13423), 'numpy.array', 'np.array', (['[self.dict_claim_lengths[q] for q in self.claims]'], {}), '([self.dict_claim_lengths[q] for q in self.claims])\n', (13372, 13423), True, 'import numpy as np\n'), ((13460, 13519), 'numpy.array', 'np.array', (['[self.dict_char_left_src[q] for q in self.claims]'], {}), '([self.dict_char_left_src[q] for q in self.claims])\n', (13468, 13519), True, 'import numpy as np\n'), ((13551, 13612), 'numpy.array', 'np.array', (['[self.dict_query_positions[q] for q in self.claims]'], {}), '([self.dict_query_positions[q] for q in self.claims])\n', (13559, 13612), True, 'import numpy as np\n'), ((13641, 13696), 'numpy.array', 'np.array', (['[self.dict_query_adj[q] for q in self.claims]'], {}), '([self.dict_query_adj[q] for q in self.claims])\n', (13649, 13696), True, 'import numpy as np\n'), ((17785, 17814), 'collections.defaultdict', 'collections.defaultdict', (['list'], {}), '(list)\n', (17808, 17814), False, 'import collections\n'), ((359, 381), 'numpy.power', 'np.power', (['rowsum', '(-0.5)'], {}), '(rowsum, -0.5)\n', (367, 381), True, 'import numpy as np\n'), ((5957, 5970), 'numpy.array', 'np.array', (['ids'], {}), '(ids)\n', (5965, 5970), True, 'import numpy as np\n'), ((6492, 6521), 'collections.defaultdict', 'collections.defaultdict', (['list'], {}), '(list)\n', (6515, 6521), False, 'import collections\n'), ((7311, 7328), 'numpy.array', 'np.array', (['queries'], {}), '(queries)\n', (7319, 7328), True, 'import numpy as np\n'), ((7330, 7344), 'numpy.array', 'np.array', (['docs'], {}), '(docs)\n', (7338, 7344), True, 'import numpy as np\n'), ((12402, 12415), 'numpy.array', 'np.array', (['ids'], {}), '(ids)\n', (12410, 12415), True, 'import numpy as np\n'), ((16148, 16161), 'numpy.array', 'np.array', (['ids'], {}), '(ids)\n', (16156, 16161), True, 'import numpy as np\n'), ((17205, 17218), 'numpy.array', 'np.array', (['adj'], {}), '(adj)\n', (17213, 17218), True, 'import numpy as np\n'), ((18659, 18676), 'numpy.array', 'np.array', (['queries'], {}), '(queries)\n', (18667, 18676), True, 'import numpy as np\n'), ((18678, 18702), 'numpy.array', 'np.array', (['queries_labels'], {}), '(queries_labels)\n', (18686, 18702), True, 'import numpy as np\n'), ((5878, 5896), 'numpy.arange', 'np.arange', (['length_'], {}), '(length_)\n', (5887, 5896), True, 'import numpy as np\n'), ((11906, 11924), 'numpy.arange', 'np.arange', (['length_'], {}), '(length_)\n', (11915, 11924), True, 'import numpy as np\n'), ((15882, 15900), 'numpy.arange', 'np.arange', (['length_'], {}), '(length_)\n', (15891, 15900), True, 'import numpy as np\n')] |
'''
Wrapper for all FeatureExtraction algorithm
'''
import numpy as np
from python_speech_features import mfcc
import rasta
'''
Leave the data as raw
'''
class Raw:
def __call__(self, X, rate):
return X
'''
FeatureExtraction using Mfcc
https://medium.com/@jonathan_hui/speech-recognition-feature-extraction-mfcc-plp-5455f5a69dd9
'''
class Mfcc:
def __init__(self, flatten=True):
self.flatten = flatten
def __call__(self, X, rate):
ret = []
for signal in X:
features = mfcc(signal,rate)
if self.flatten:
features = features.flatten()
ret.append(features)
return np.array(ret)
class Rasta:
def __call__(self, X, rate):
ret = []
for signal in X:
features = rasta.rastaplp(signal.astype(np.float32), rate, dorasta=True).flatten()
ret.append(features)
return np.array(ret)
| [
"python_speech_features.mfcc",
"numpy.array"
] | [((669, 682), 'numpy.array', 'np.array', (['ret'], {}), '(ret)\n', (677, 682), True, 'import numpy as np\n'), ((916, 929), 'numpy.array', 'np.array', (['ret'], {}), '(ret)\n', (924, 929), True, 'import numpy as np\n'), ((528, 546), 'python_speech_features.mfcc', 'mfcc', (['signal', 'rate'], {}), '(signal, rate)\n', (532, 546), False, 'from python_speech_features import mfcc\n')] |
import numpy as np
class RLS:
def __init__(self):
"""
RLS initialisation
"""
self.P = np.eye(2) # state matrix, 2x2
self.w = np.zeros(
(2, 1)
) # weights (coefficients of the linear model including constant, 2x1)
self.error = 0
def update(self, x: float, y: float):
"""
RLS state update
:param x: past/input observation (scalar)
:param y: current/output observation (scalar)
"""
X = np.reshape([1, x], (1, 2)) # reshape to a 1x2 matrix
alpha = float(y - X @ self.w)
g = (self.P @ X.T) / (1 + X @ self.P @ X.T)
self.error = np.abs(alpha)
self.w = self.w + g * alpha
self.P = self.P - g * X * self.P
def predict(self, x: float) -> float:
"""
Predict observation, using RLS model
:param x: past observation (scalar)
:return: predicted observation (scalar)
"""
X = np.reshape([1, x], (1, 2)) # reshape to a 1x2 matrix
return float(X @ self.w)
| [
"numpy.eye",
"numpy.zeros",
"numpy.reshape",
"numpy.abs"
] | [((125, 134), 'numpy.eye', 'np.eye', (['(2)'], {}), '(2)\n', (131, 134), True, 'import numpy as np\n'), ((173, 189), 'numpy.zeros', 'np.zeros', (['(2, 1)'], {}), '((2, 1))\n', (181, 189), True, 'import numpy as np\n'), ((514, 540), 'numpy.reshape', 'np.reshape', (['[1, x]', '(1, 2)'], {}), '([1, x], (1, 2))\n', (524, 540), True, 'import numpy as np\n'), ((679, 692), 'numpy.abs', 'np.abs', (['alpha'], {}), '(alpha)\n', (685, 692), True, 'import numpy as np\n'), ((987, 1013), 'numpy.reshape', 'np.reshape', (['[1, x]', '(1, 2)'], {}), '([1, x], (1, 2))\n', (997, 1013), True, 'import numpy as np\n')] |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Problem 038
Transpose and Flatten
Source : https://www.hackerrank.com/challenges/np-transpose-and-flatten/problem
"""
import numpy as np
n, m = map(int, input().split())
ar = np.array([input().split() for _ in range(n)], int)
print(np.transpose(ar))
print(ar.flatten())
| [
"numpy.transpose"
] | [((286, 302), 'numpy.transpose', 'np.transpose', (['ar'], {}), '(ar)\n', (298, 302), True, 'import numpy as np\n')] |
#!/usr/bin/env python3
# NDCG scoring function adapted from: https://github.com/kmbnw/rank_metrics/blob/master/python/ndcg.py
import json
import logging
import warnings
from collections import OrderedDict
from typing import Dict, List, Iterable
import numpy as np
import pandas as pd
try:
from tqdm import tqdm
except ImportError:
def tqdm(iterable: Iterable, **kwargs) -> Iterable:
return iterable
logging.basicConfig(level=logging.DEBUG)
def process_expert_gold(expert_preds: List) -> Dict[str, Dict[str, float]]:
return {
pred["qid".lower()]: {
data["uuid"]: data["relevance"] for data in pred["documents"]
}
for pred in expert_preds
}
def process_expert_pred(
filepath_or_buffer: str, sep: str = "\t"
) -> Dict[str, List[str]]:
df = pd.read_csv(
filepath_or_buffer, sep=sep, names=("question", "explanation"), dtype=str
)
if any(df[field].isnull().all() for field in df.columns):
raise ValueError(
"invalid format of the prediction dataset, possibly the wrong separator"
)
pred: Dict[str, List[str]] = OrderedDict()
for id, df_explanations in df.groupby("question"):
pred[id] = list(
OrderedDict.fromkeys(df_explanations["explanation"].str.lower())
)
return pred
def main():
import argparse
parser = argparse.ArgumentParser()
parser.add_argument(
"--gold", type=argparse.FileType("r", encoding="UTF-8"), required=True
)
parser.add_argument("--no-tqdm", action="store_false", dest="tqdm")
parser.add_argument("pred", type=argparse.FileType("r", encoding="UTF-8"))
args = parser.parse_args()
preds = process_expert_pred(args.pred)
gold_explanations = process_expert_gold(json.load(args.gold)["rankingProblems"])
rating_threshold = 0
ndcg_score = mean_average_ndcg(gold_explanations, preds, rating_threshold, args.tqdm)
print(f"Mean NDCG Score : {ndcg_score}")
def mean_average_ndcg(
gold: Dict[str, Dict[str, float]],
predicted: Dict[str, List[str]],
rating_threshold: int,
use_tqdm: bool
) -> float:
"""Calculate the Mean Average NDCG
Args:
gold (Dict[str, Dict[str, float]]): Gold explanations with Question_ID: [{fact_id_1: score_1}, {fact_id_2}:score]
predicted (Dict[str, List[str]]): Predicted explanations with Question_ID: [fact_id_1, fact_id_2]
rating_threshold (int): The threshold rating from gold explanations used to calcuate NDCG
Returns:
float: returns Mean Average NDCG score or -1 (if proper gold data is not provided)
"""
if len(gold) == 0:
logging.error(
"Empty gold labels. Please verify if you have provided the correct file"
)
return -1
if use_tqdm:
mean_average_ndcg = np.average(
[
ndcg(
gold[q_id],
list(OrderedDict.fromkeys(predicted[q_id]))
if q_id in predicted
else [],
rating_threshold,
)
for q_id in tqdm(gold, "evaluating")
]
)
else:
mean_average_ndcg = np.average(
[
ndcg(
gold[q_id],
list(OrderedDict.fromkeys(predicted[q_id]))
if q_id in predicted
else [],
rating_threshold,
)
for q_id in gold
]
)
return mean_average_ndcg
def ndcg(
gold: Dict[str, float],
predicted: List[str],
rating_threshold: int,
alternate: bool = True,
) -> float:
"""Calculate NDCG value for individual Question-Explanations Pair
Args:
gold (Dict[str, float]): Gold expert ratings
predicted (List[str]): List of predicted ids
rating_threshold (int): Threshold of gold ratings to consider for NDCG calcuation
alternate (bool, optional): True to use the alternate scoring (intended to place more emphasis on relevant results). Defaults to True.
Raises:
Exception: If ids are missing from prediction. Raises warning.
Returns:
float: NDCG score
"""
if len(gold) == 0:
return 1
# Only consider relevance scores greater than 0
relevance = np.array(
[
gold[f_id] if f_id in gold and gold[f_id] > rating_threshold else 0
for f_id in predicted
]
)
missing_ids = [g_id for g_id in gold if g_id not in predicted]
if len(missing_ids) > 0:
warnings.warn(
f"Missing gold ids from prediction. Missing ids will be appended to 10**6 position"
)
padded = np.zeros(10 ** 6)
for index, g_id in enumerate(missing_ids):
padded[index] = gold[g_id]
relevance = np.concatenate((relevance, np.flip(padded)), axis=0)
nranks = len(relevance)
if relevance is None or len(relevance) < 1:
return 0.0
if nranks < 1:
raise Exception("nranks < 1")
pad = max(0, nranks - len(relevance))
# pad could be zero in which case this will no-op
relevance = np.pad(relevance, (0, pad), "constant")
# now slice downto nranks
relevance = relevance[0 : min(nranks, len(relevance))]
ideal_dcg = idcg(relevance, alternate)
if ideal_dcg == 0:
return 0.0
return dcg(relevance, alternate) / ideal_dcg
def dcg(relevance: np.array, alternate: bool = True) -> float:
"""Calculate discounted cumulative gain.
Args:
relevance (np.array): Graded and ordered relevances of the results.
alternate (bool, optional): True to use the alternate scoring (intended to place more emphasis on relevant results). Defaults to True.
Returns:
float: DCG score
"""
if relevance is None or len(relevance) < 1:
return 0.0
p = len(relevance)
if alternate:
# from wikipedia: "An alternative formulation of
# DCG[5] places stronger emphasis on retrieving relevant documents"
log2i = np.log2(np.asarray(range(1, p + 1)) + 1)
return ((np.power(2, relevance) - 1) / log2i).sum()
else:
log2i = np.log2(range(2, p + 1))
return relevance[0] + (relevance[1:] / log2i).sum()
def idcg(relevance: np.array, alternate: bool = True) -> float:
"""Calculate ideal discounted cumulative gain (maximum possible DCG)
Args:
relevance (np.array): Graded and ordered relevances of the results
alternate (bool, optional): True to use the alternate scoring (intended to place more emphasis on relevant results).. Defaults to True.
Returns:
float: IDCG Score
"""
if relevance is None or len(relevance) < 1:
return 0.0
# guard copy before sort
rel = relevance.copy()
rel.sort()
return dcg(rel[::-1], alternate)
if __name__ == "__main__":
main()
| [
"numpy.pad",
"logging.error",
"json.load",
"numpy.flip",
"argparse.ArgumentParser",
"logging.basicConfig",
"tqdm.tqdm",
"pandas.read_csv",
"numpy.power",
"numpy.zeros",
"collections.OrderedDict.fromkeys",
"numpy.array",
"collections.OrderedDict",
"warnings.warn",
"argparse.FileType"
] | [((419, 459), 'logging.basicConfig', 'logging.basicConfig', ([], {'level': 'logging.DEBUG'}), '(level=logging.DEBUG)\n', (438, 459), False, 'import logging\n'), ((813, 903), 'pandas.read_csv', 'pd.read_csv', (['filepath_or_buffer'], {'sep': 'sep', 'names': "('question', 'explanation')", 'dtype': 'str'}), "(filepath_or_buffer, sep=sep, names=('question', 'explanation'),\n dtype=str)\n", (824, 903), True, 'import pandas as pd\n'), ((1132, 1145), 'collections.OrderedDict', 'OrderedDict', ([], {}), '()\n', (1143, 1145), False, 'from collections import OrderedDict\n'), ((1379, 1404), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (1402, 1404), False, 'import argparse\n'), ((4378, 4485), 'numpy.array', 'np.array', (['[(gold[f_id] if f_id in gold and gold[f_id] > rating_threshold else 0) for\n f_id in predicted]'], {}), '([(gold[f_id] if f_id in gold and gold[f_id] > rating_threshold else\n 0) for f_id in predicted])\n', (4386, 4485), True, 'import numpy as np\n'), ((5222, 5261), 'numpy.pad', 'np.pad', (['relevance', '(0, pad)', '"""constant"""'], {}), "(relevance, (0, pad), 'constant')\n", (5228, 5261), True, 'import numpy as np\n'), ((2668, 2760), 'logging.error', 'logging.error', (['"""Empty gold labels. Please verify if you have provided the correct file"""'], {}), "(\n 'Empty gold labels. Please verify if you have provided the correct file')\n", (2681, 2760), False, 'import logging\n'), ((4634, 4742), 'warnings.warn', 'warnings.warn', (['f"""Missing gold ids from prediction. Missing ids will be appended to 10**6 position"""'], {}), "(\n f'Missing gold ids from prediction. Missing ids will be appended to 10**6 position'\n )\n", (4647, 4742), False, 'import warnings\n'), ((4772, 4789), 'numpy.zeros', 'np.zeros', (['(10 ** 6)'], {}), '(10 ** 6)\n', (4780, 4789), True, 'import numpy as np\n'), ((1453, 1493), 'argparse.FileType', 'argparse.FileType', (['"""r"""'], {'encoding': '"""UTF-8"""'}), "('r', encoding='UTF-8')\n", (1470, 1493), False, 'import argparse\n'), ((1624, 1664), 'argparse.FileType', 'argparse.FileType', (['"""r"""'], {'encoding': '"""UTF-8"""'}), "('r', encoding='UTF-8')\n", (1641, 1664), False, 'import argparse\n'), ((1785, 1805), 'json.load', 'json.load', (['args.gold'], {}), '(args.gold)\n', (1794, 1805), False, 'import json\n'), ((4927, 4942), 'numpy.flip', 'np.flip', (['padded'], {}), '(padded)\n', (4934, 4942), True, 'import numpy as np\n'), ((3140, 3164), 'tqdm.tqdm', 'tqdm', (['gold', '"""evaluating"""'], {}), "(gold, 'evaluating')\n", (3144, 3164), False, 'from tqdm import tqdm\n'), ((6192, 6214), 'numpy.power', 'np.power', (['(2)', 'relevance'], {}), '(2, relevance)\n', (6200, 6214), True, 'import numpy as np\n'), ((2947, 2984), 'collections.OrderedDict.fromkeys', 'OrderedDict.fromkeys', (['predicted[q_id]'], {}), '(predicted[q_id])\n', (2967, 2984), False, 'from collections import OrderedDict\n'), ((3332, 3369), 'collections.OrderedDict.fromkeys', 'OrderedDict.fromkeys', (['predicted[q_id]'], {}), '(predicted[q_id])\n', (3352, 3369), False, 'from collections import OrderedDict\n')] |
#!/usr/bin/env python
"""
This is a demo, showing how to work with a "tree" structure
It demonstrates moving objects around, etc, etc.
"""
import wx
#ver = 'local'
ver = 'installed'
if ver == 'installed': ## import the installed version
from wx.lib.floatcanvas import NavCanvas, Resources
from wx.lib.floatcanvas import FloatCanvas as FC
from wx.lib.floatcanvas.Utilities import BBox
print("using installed version: %s" % wx.lib.floatcanvas.__version__)
elif ver == 'local':
## import a local version
import sys
sys.path.append("..")
from floatcanvas import NavCanvas, Resources
from floatcanvas import FloatCanvas as FC
from floatcanvas.Utilities import BBox
import numpy as N
## here we create some new mixins:
## fixme: These really belong in floatcanvas package -- but I kind of want to clean it up some first
class MovingObjectMixin:
"""
Methods required for a Moving object
"""
def GetOutlinePoints(self):
"""
Returns a set of points with which to draw the outline when moving the
object.
Points are a NX2 array of (x,y) points in World coordinates.
"""
BB = self.BoundingBox
OutlinePoints = N.array( ( (BB[0,0], BB[0,1]),
(BB[0,0], BB[1,1]),
(BB[1,0], BB[1,1]),
(BB[1,0], BB[0,1]),
)
)
return OutlinePoints
class ConnectorObjectMixin:
"""
Mixin class for DrawObjects that can be connected with lines
Note that this version only works for Objects that have an "XY" attribute:
that is, one that is derived from XHObjectMixin.
"""
def GetConnectPoint(self):
return self.XY
class MovingBitmap(FC.ScaledBitmap, MovingObjectMixin, ConnectorObjectMixin):
"""
ScaledBitmap Object that can be moved
"""
## All we need to do is is inherit from:
## ScaledBitmap, MovingObjectMixin and ConnectorObjectMixin
pass
class MovingCircle(FC.Circle, MovingObjectMixin, ConnectorObjectMixin):
"""
ScaledBitmap Object that can be moved
"""
## All we need to do is is inherit from:
## Circle MovingObjectMixin and ConnectorObjectMixin
pass
class MovingGroup(FC.Group, MovingObjectMixin, ConnectorObjectMixin):
def GetConnectPoint(self):
return self.BoundingBox.Center
class NodeObject(FC.Group, MovingObjectMixin, ConnectorObjectMixin):
"""
A version of the moving group for nodes -- an ellipse with text on it.
"""
def __init__(self,
Label,
XY,
WH,
BackgroundColor = "Yellow",
TextColor = "Black",
InForeground = False,
IsVisible = True):
XY = N.asarray(XY, N.float).reshape(2,)
WH = N.asarray(WH, N.float).reshape(2,)
Label = FC.ScaledText(Label,
XY,
Size = WH[1] / 2.0,
Color = TextColor,
Position = 'cc',
)
self.Ellipse = FC.Ellipse( (XY - WH/2.0),
WH,
FillColor = BackgroundColor,
LineStyle = None,
)
FC.Group.__init__(self, [self.Ellipse, Label], InForeground, IsVisible)
def GetConnectPoint(self):
return self.BoundingBox.Center
class MovingText(FC.ScaledText, MovingObjectMixin, ConnectorObjectMixin):
"""
ScaledBitmap Object that can be moved
"""
## All we need to do is is inherit from:
## ScaledBitmap, MovingObjectMixin and ConnectorObjectMixin
pass
class ConnectorLine(FC.LineOnlyMixin, FC.DrawObject,):
"""
A Line that connects two objects -- it uses the objects to get its coordinates
The objects must have a GetConnectPoint() method.
"""
##fixme: this should be added to the Main FloatCanvas Objects some day.
def __init__(self,
Object1,
Object2,
LineColor = "Black",
LineStyle = "Solid",
LineWidth = 1,
InForeground = False):
FC.DrawObject.__init__(self, InForeground)
self.Object1 = Object1
self.Object2 = Object2
self.LineColor = LineColor
self.LineStyle = LineStyle
self.LineWidth = LineWidth
self.CalcBoundingBox()
self.SetPen(LineColor,LineStyle,LineWidth)
self.HitLineWidth = max(LineWidth,self.MinHitLineWidth)
def CalcBoundingBox(self):
self.BoundingBox = BBox.fromPoints((self.Object1.GetConnectPoint(),
self.Object2.GetConnectPoint()) )
if self._Canvas:
self._Canvas.BoundingBoxDirty = True
def _Draw(self, dc , WorldToPixel, ScaleWorldToPixel, HTdc=None):
Points = N.array( (self.Object1.GetConnectPoint(),
self.Object2.GetConnectPoint()) )
Points = WorldToPixel(Points)
dc.SetPen(self.Pen)
dc.DrawLines(Points)
if HTdc and self.HitAble:
HTdc.SetPen(self.HitPen)
HTdc.DrawLines(Points)
class TriangleShape1(FC.Polygon, MovingObjectMixin):
def __init__(self, XY, L):
"""
An equilateral triangle object
XY is the middle of the triangle
L is the length of one side of the Triangle
"""
XY = N.asarray(XY)
XY.shape = (2,)
Points = self.CompPoints(XY, L)
FC.Polygon.__init__(self, Points,
LineColor = "Black",
LineStyle = "Solid",
LineWidth = 2,
FillColor = "Red",
FillStyle = "Solid")
## Override the default OutlinePoints
def GetOutlinePoints(self):
return self.Points
def CompPoints(self, XY, L):
c = L/ N.sqrt(3)
Points = N.array(((0, c),
( L/2.0, -c/2.0),
(-L/2.0, -c/2.0)),
N.float_)
Points += XY
return Points
### Tree Utilities
### And some hard coded data...
class TreeNode:
dx = 15
dy = 4
def __init__(self, name, Children = []):
self.Name = name
#self.parent = None -- Is this needed?
self.Children = Children
self.Point = None # The coords of the node.
def __str__(self):
return "TreeNode: %s"%self.Name
__repr__ = __str__
## Build Tree:
leaves = [TreeNode(name) for name in ["Assistant VP 1","Assistant VP 2","Assistant VP 3"] ]
VP1 = TreeNode("VP1", Children = leaves)
VP2 = TreeNode("VP2")
CEO = TreeNode("CEO", [VP1, VP2])
Father = TreeNode("Father", [TreeNode("Daughter"), TreeNode("Son")])
elements = TreeNode("Root", [CEO, Father])
def LayoutTree(root, x, y, level):
NumNodes = len(root.Children)
root.Point = (x,y)
x += root.dx
y += (root.dy * level * (NumNodes-1) / 2.0)
for node in root.Children:
LayoutTree(node, x, y, level-1)
y -= root.dy * level
def TraverseTree(root, func):
func(root)
for child in (root.Children):
TraverseTree(child, func)
class DrawFrame(wx.Frame):
"""
A simple frame used for the Demo
"""
def __init__(self, *args, **kwargs):
wx.Frame.__init__(self, *args, **kwargs)
self.CreateStatusBar()
# Add the Canvas
Canvas = NavCanvas.NavCanvas(self,-1,(500,500),
ProjectionFun = None,
Debug = 0,
BackgroundColor = "White",
).Canvas
self.Canvas = Canvas
Canvas.Bind(FC.EVT_MOTION, self.OnMove )
Canvas.Bind(FC.EVT_LEFT_UP, self.OnLeftUp )
self.elements = elements
LayoutTree(self.elements, 0, 0, 3)
self.AddTree(self.elements)
self.Show(True)
self.Canvas.ZoomToBB()
self.MoveObject = None
self.Moving = False
return None
def AddTree(self, root):
Nodes = []
Connectors = []
EllipseW = 15
EllipseH = 4
def CreateObject(node):
if node.Children:
object = NodeObject(node.Name,
node.Point,
(15, 4),
BackgroundColor = "Yellow",
TextColor = "Black",
)
else:
object = MovingText(node.Name,
node.Point,
2.0,
BackgroundColor = "Yellow",
Color = "Red",
Position = "cl",
)
node.DrawObject = object
Nodes.append(object)
def AddConnectors(node):
for child in node.Children:
Connector = ConnectorLine(node.DrawObject, child.DrawObject, LineWidth=3, LineColor="Red")
Connectors.append(Connector)
## create the Objects
TraverseTree(root, CreateObject)
## create the Connectors
TraverseTree(root, AddConnectors)
## Add the conenctos to the Canvas first, so they are undernieth the nodes
self.Canvas.AddObjects(Connectors)
## now add the nodes
self.Canvas.AddObjects(Nodes)
# Now bind the Nodes -- DrawObjects must be Added to a Canvas before they can be bound.
for node in Nodes:
#pass
node.Bind(FC.EVT_FC_LEFT_DOWN, self.ObjectHit)
def ObjectHit(self, object):
if not self.Moving:
self.Moving = True
self.StartPoint = object.HitCoordsPixel
self.StartObject = self.Canvas.WorldToPixel(object.GetOutlinePoints())
self.MoveObject = None
self.MovingObject = object
def OnMove(self, event):
"""
Updates the status bar with the world coordinates
and moves the object it is clicked on
"""
self.SetStatusText("%.4f, %.4f"%tuple(event.Coords))
if self.Moving:
dxy = event.GetPosition() - self.StartPoint
# Draw the Moving Object:
dc = wx.ClientDC(self.Canvas)
dc.SetPen(wx.Pen('WHITE', 2, wx.SHORT_DASH))
dc.SetBrush(wx.TRANSPARENT_BRUSH)
dc.SetLogicalFunction(wx.XOR)
if self.MoveObject is not None:
dc.DrawPolygon(self.MoveObject)
self.MoveObject = self.StartObject + dxy
dc.DrawPolygon(self.MoveObject)
def OnLeftUp(self, event):
if self.Moving:
self.Moving = False
if self.MoveObject is not None:
dxy = event.GetPosition() - self.StartPoint
dxy = self.Canvas.ScalePixelToWorld(dxy)
self.MovingObject.Move(dxy)
self.MoveTri = None
self.Canvas.Draw(True)
app = wx.App(0)
DrawFrame(None, -1, "FloatCanvas Tree Demo App", wx.DefaultPosition, (700,700) )
app.MainLoop()
| [
"sys.path.append",
"floatcanvas.FloatCanvas.DrawObject.__init__",
"floatcanvas.FloatCanvas.Polygon.__init__",
"floatcanvas.FloatCanvas.ScaledText",
"numpy.asarray",
"floatcanvas.NavCanvas.NavCanvas",
"floatcanvas.FloatCanvas.Group.__init__",
"wx.Frame.__init__",
"wx.App",
"numpy.array",
"wx.Clie... | [((11412, 11421), 'wx.App', 'wx.App', (['(0)'], {}), '(0)\n', (11418, 11421), False, 'import wx\n'), ((546, 567), 'sys.path.append', 'sys.path.append', (['""".."""'], {}), "('..')\n", (561, 567), False, 'import sys\n'), ((1224, 1325), 'numpy.array', 'N.array', (['((BB[0, 0], BB[0, 1]), (BB[0, 0], BB[1, 1]), (BB[1, 0], BB[1, 1]), (BB[1, 0\n ], BB[0, 1]))'], {}), '(((BB[0, 0], BB[0, 1]), (BB[0, 0], BB[1, 1]), (BB[1, 0], BB[1, 1]),\n (BB[1, 0], BB[0, 1])))\n', (1231, 1325), True, 'import numpy as N\n'), ((2982, 3056), 'floatcanvas.FloatCanvas.ScaledText', 'FC.ScaledText', (['Label', 'XY'], {'Size': '(WH[1] / 2.0)', 'Color': 'TextColor', 'Position': '"""cc"""'}), "(Label, XY, Size=WH[1] / 2.0, Color=TextColor, Position='cc')\n", (2995, 3056), True, 'from floatcanvas import FloatCanvas as FC\n'), ((3208, 3280), 'floatcanvas.FloatCanvas.Ellipse', 'FC.Ellipse', (['(XY - WH / 2.0)', 'WH'], {'FillColor': 'BackgroundColor', 'LineStyle': 'None'}), '(XY - WH / 2.0, WH, FillColor=BackgroundColor, LineStyle=None)\n', (3218, 3280), True, 'from floatcanvas import FloatCanvas as FC\n'), ((3420, 3491), 'floatcanvas.FloatCanvas.Group.__init__', 'FC.Group.__init__', (['self', '[self.Ellipse, Label]', 'InForeground', 'IsVisible'], {}), '(self, [self.Ellipse, Label], InForeground, IsVisible)\n', (3437, 3491), True, 'from floatcanvas import FloatCanvas as FC\n'), ((4337, 4379), 'floatcanvas.FloatCanvas.DrawObject.__init__', 'FC.DrawObject.__init__', (['self', 'InForeground'], {}), '(self, InForeground)\n', (4359, 4379), True, 'from floatcanvas import FloatCanvas as FC\n'), ((5609, 5622), 'numpy.asarray', 'N.asarray', (['XY'], {}), '(XY)\n', (5618, 5622), True, 'import numpy as N\n'), ((5697, 5821), 'floatcanvas.FloatCanvas.Polygon.__init__', 'FC.Polygon.__init__', (['self', 'Points'], {'LineColor': '"""Black"""', 'LineStyle': '"""Solid"""', 'LineWidth': '(2)', 'FillColor': '"""Red"""', 'FillStyle': '"""Solid"""'}), "(self, Points, LineColor='Black', LineStyle='Solid',\n LineWidth=2, FillColor='Red', FillStyle='Solid')\n", (5716, 5821), True, 'from floatcanvas import FloatCanvas as FC\n'), ((6185, 6255), 'numpy.array', 'N.array', (['((0, c), (L / 2.0, -c / 2.0), (-L / 2.0, -c / 2.0))', 'N.float_'], {}), '(((0, c), (L / 2.0, -c / 2.0), (-L / 2.0, -c / 2.0)), N.float_)\n', (6192, 6255), True, 'import numpy as N\n'), ((7576, 7616), 'wx.Frame.__init__', 'wx.Frame.__init__', (['self', '*args'], {}), '(self, *args, **kwargs)\n', (7593, 7616), False, 'import wx\n'), ((6157, 6166), 'numpy.sqrt', 'N.sqrt', (['(3)'], {}), '(3)\n', (6163, 6166), True, 'import numpy as N\n'), ((7691, 7790), 'floatcanvas.NavCanvas.NavCanvas', 'NavCanvas.NavCanvas', (['self', '(-1)', '(500, 500)'], {'ProjectionFun': 'None', 'Debug': '(0)', 'BackgroundColor': '"""White"""'}), "(self, -1, (500, 500), ProjectionFun=None, Debug=0,\n BackgroundColor='White')\n", (7710, 7790), False, 'from floatcanvas import NavCanvas, Resources\n'), ((10682, 10706), 'wx.ClientDC', 'wx.ClientDC', (['self.Canvas'], {}), '(self.Canvas)\n', (10693, 10706), False, 'import wx\n'), ((2883, 2905), 'numpy.asarray', 'N.asarray', (['XY', 'N.float'], {}), '(XY, N.float)\n', (2892, 2905), True, 'import numpy as N\n'), ((2931, 2953), 'numpy.asarray', 'N.asarray', (['WH', 'N.float'], {}), '(WH, N.float)\n', (2940, 2953), True, 'import numpy as N\n'), ((10729, 10762), 'wx.Pen', 'wx.Pen', (['"""WHITE"""', '(2)', 'wx.SHORT_DASH'], {}), "('WHITE', 2, wx.SHORT_DASH)\n", (10735, 10762), False, 'import wx\n')] |
from slm_lab.experiment.control import make_agent_env
from slm_lab.lib import util
from slm_lab.spec import spec_util
import numpy as np
import pandas as pd
import pytest
@pytest.fixture(scope='session')
def test_spec():
spec = spec_util.get('experimental/misc/base.json', 'base_case_openai')
spec_util.tick(spec, 'trial')
spec = spec_util.override_test_spec(spec)
return spec
@pytest.fixture
def test_df():
data = pd.DataFrame({
'integer': [1, 2, 3],
'square': [1, 4, 9],
'letter': ['a', 'b', 'c'],
})
assert isinstance(data, pd.DataFrame)
return data
@pytest.fixture
def test_dict():
data = {
'a': 1,
'b': 2,
'c': 3,
}
assert isinstance(data, dict)
return data
@pytest.fixture
def test_list():
data = [1, 2, 3]
assert isinstance(data, list)
return data
@pytest.fixture
def test_obj():
class Foo:
bar = 'bar'
return Foo()
@pytest.fixture
def test_str():
data = 'lorem ipsum dolor'
assert isinstance(data, str)
return data
@pytest.fixture(scope='session', params=[
(
2,
[
[np.asarray([1, 1, 1, 1]), 1, 1, np.asarray([2, 2, 2, 2]), 1],
[np.asarray([2, 2, 2, 2]), 1, 2, np.asarray([3, 3, 3, 3]), 2],
[np.asarray([3, 3, 3, 3]), 1, 3, np.asarray([4, 4, 4, 4]), 3],
[np.asarray([4, 4, 4, 4]), 1, 4, np.asarray([5, 5, 5, 5]), 4],
[np.asarray([5, 5, 5, 5]), 1, 5, np.asarray([6, 6, 6, 6]), 5],
[np.asarray([6, 6, 6, 6]), 1, 6, np.asarray([7, 7, 7, 7]), 6],
[np.asarray([7, 7, 7, 7]), 1, 7, np.asarray([8, 8, 8, 8]), 7],
[np.asarray([8, 8, 8, 8]), 1, 8, np.asarray([9, 9, 9, 9]), 8],
]
),
])
def test_memory(request):
spec = spec_util.get('experimental/misc/base.json', 'base_memory')
spec_util.tick(spec, 'trial')
agent, env = make_agent_env(spec)
res = (agent.body.memory, ) + request.param
return res
@pytest.fixture(scope='session', params=[
(
2,
[
[np.asarray([1, 1, 1, 1]), 1, 1, np.asarray([2, 2, 2, 2]), 0],
[np.asarray([2, 2, 2, 2]), 1, 2, np.asarray([3, 3, 3, 3]), 0],
[np.asarray([3, 3, 3, 3]), 1, 3, np.asarray([4, 4, 4, 4]), 0],
[np.asarray([4, 4, 4, 4]), 1, 4, np.asarray([5, 5, 5, 5]), 0],
[np.asarray([5, 5, 5, 5]), 1, 5, np.asarray([6, 6, 6, 6]), 0],
[np.asarray([6, 6, 6, 6]), 1, 6, np.asarray([7, 7, 7, 7]), 0],
[np.asarray([7, 7, 7, 7]), 1, 7, np.asarray([8, 8, 8, 8]), 0],
[np.asarray([8, 8, 8, 8]), 1, 8, np.asarray([9, 9, 9, 9]), 1],
]
),
])
def test_on_policy_episodic_memory(request):
spec = spec_util.get('experimental/misc/base.json', 'base_on_policy_memory')
spec_util.tick(spec, 'trial')
agent, env = make_agent_env(spec)
res = (agent.body.memory, ) + request.param
return res
@pytest.fixture(scope='session', params=[
(
4,
[
[np.asarray([1, 1, 1, 1]), 1, 1, np.asarray([2, 2, 2, 2]), 0],
[np.asarray([2, 2, 2, 2]), 1, 2, np.asarray([3, 3, 3, 3]), 0],
[np.asarray([3, 3, 3, 3]), 1, 3, np.asarray([4, 4, 4, 4]), 0],
[np.asarray([4, 4, 4, 4]), 1, 4, np.asarray([5, 5, 5, 5]), 0],
[np.asarray([5, 5, 5, 5]), 1, 5, np.asarray([6, 6, 6, 6]), 0],
[np.asarray([6, 6, 6, 6]), 1, 6, np.asarray([7, 7, 7, 7]), 0],
[np.asarray([7, 7, 7, 7]), 1, 7, np.asarray([8, 8, 8, 8]), 0],
[np.asarray([8, 8, 8, 8]), 1, 8, np.asarray([9, 9, 9, 9]), 1],
]
),
])
def test_on_policy_batch_memory(request):
spec = spec_util.get('experimental/misc/base.json', 'base_on_policy_batch_memory')
spec_util.tick(spec, 'trial')
agent, env = make_agent_env(spec)
res = (agent.body.memory, ) + request.param
return res
@pytest.fixture(scope='session', params=[
(
4,
[
[np.asarray([1, 1, 1, 1]), 1, 1, np.asarray([2, 2, 2, 2]), 0, 1000],
[np.asarray([2, 2, 2, 2]), 1, 2, np.asarray([3, 3, 3, 3]), 0, 0],
[np.asarray([3, 3, 3, 3]), 1, 3, np.asarray([4, 4, 4, 4]), 0, 0],
[np.asarray([4, 4, 4, 4]), 1, 4, np.asarray([5, 5, 5, 5]), 0, 0],
[np.asarray([5, 5, 5, 5]), 1, 5, np.asarray([6, 6, 6, 6]), 0, 1000],
[np.asarray([6, 6, 6, 6]), 1, 6, np.asarray([7, 7, 7, 7]), 0, 0],
[np.asarray([7, 7, 7, 7]), 1, 7, np.asarray([8, 8, 8, 8]), 0, 0],
[np.asarray([8, 8, 8, 8]), 1, 8, np.asarray([9, 9, 9, 9]), 1, 1000],
]
),
])
def test_prioritized_replay_memory(request):
spec = spec_util.get('experimental/misc/base.json', 'base_prioritized_replay_memory')
spec_util.tick(spec, 'trial')
agent, env = make_agent_env(spec)
res = (agent.body.memory, ) + request.param
return res
| [
"pandas.DataFrame",
"slm_lab.spec.spec_util.tick",
"numpy.asarray",
"slm_lab.spec.spec_util.override_test_spec",
"pytest.fixture",
"slm_lab.spec.spec_util.get",
"slm_lab.experiment.control.make_agent_env"
] | [((174, 205), 'pytest.fixture', 'pytest.fixture', ([], {'scope': '"""session"""'}), "(scope='session')\n", (188, 205), False, 'import pytest\n'), ((234, 298), 'slm_lab.spec.spec_util.get', 'spec_util.get', (['"""experimental/misc/base.json"""', '"""base_case_openai"""'], {}), "('experimental/misc/base.json', 'base_case_openai')\n", (247, 298), False, 'from slm_lab.spec import spec_util\n'), ((303, 332), 'slm_lab.spec.spec_util.tick', 'spec_util.tick', (['spec', '"""trial"""'], {}), "(spec, 'trial')\n", (317, 332), False, 'from slm_lab.spec import spec_util\n'), ((344, 378), 'slm_lab.spec.spec_util.override_test_spec', 'spec_util.override_test_spec', (['spec'], {}), '(spec)\n', (372, 378), False, 'from slm_lab.spec import spec_util\n'), ((439, 527), 'pandas.DataFrame', 'pd.DataFrame', (["{'integer': [1, 2, 3], 'square': [1, 4, 9], 'letter': ['a', 'b', 'c']}"], {}), "({'integer': [1, 2, 3], 'square': [1, 4, 9], 'letter': ['a',\n 'b', 'c']})\n", (451, 527), True, 'import pandas as pd\n'), ((1799, 1858), 'slm_lab.spec.spec_util.get', 'spec_util.get', (['"""experimental/misc/base.json"""', '"""base_memory"""'], {}), "('experimental/misc/base.json', 'base_memory')\n", (1812, 1858), False, 'from slm_lab.spec import spec_util\n'), ((1863, 1892), 'slm_lab.spec.spec_util.tick', 'spec_util.tick', (['spec', '"""trial"""'], {}), "(spec, 'trial')\n", (1877, 1892), False, 'from slm_lab.spec import spec_util\n'), ((1910, 1930), 'slm_lab.experiment.control.make_agent_env', 'make_agent_env', (['spec'], {}), '(spec)\n', (1924, 1930), False, 'from slm_lab.experiment.control import make_agent_env\n'), ((2741, 2810), 'slm_lab.spec.spec_util.get', 'spec_util.get', (['"""experimental/misc/base.json"""', '"""base_on_policy_memory"""'], {}), "('experimental/misc/base.json', 'base_on_policy_memory')\n", (2754, 2810), False, 'from slm_lab.spec import spec_util\n'), ((2815, 2844), 'slm_lab.spec.spec_util.tick', 'spec_util.tick', (['spec', '"""trial"""'], {}), "(spec, 'trial')\n", (2829, 2844), False, 'from slm_lab.spec import spec_util\n'), ((2862, 2882), 'slm_lab.experiment.control.make_agent_env', 'make_agent_env', (['spec'], {}), '(spec)\n', (2876, 2882), False, 'from slm_lab.experiment.control import make_agent_env\n'), ((3690, 3765), 'slm_lab.spec.spec_util.get', 'spec_util.get', (['"""experimental/misc/base.json"""', '"""base_on_policy_batch_memory"""'], {}), "('experimental/misc/base.json', 'base_on_policy_batch_memory')\n", (3703, 3765), False, 'from slm_lab.spec import spec_util\n'), ((3770, 3799), 'slm_lab.spec.spec_util.tick', 'spec_util.tick', (['spec', '"""trial"""'], {}), "(spec, 'trial')\n", (3784, 3799), False, 'from slm_lab.spec import spec_util\n'), ((3817, 3837), 'slm_lab.experiment.control.make_agent_env', 'make_agent_env', (['spec'], {}), '(spec)\n', (3831, 3837), False, 'from slm_lab.experiment.control import make_agent_env\n'), ((4681, 4759), 'slm_lab.spec.spec_util.get', 'spec_util.get', (['"""experimental/misc/base.json"""', '"""base_prioritized_replay_memory"""'], {}), "('experimental/misc/base.json', 'base_prioritized_replay_memory')\n", (4694, 4759), False, 'from slm_lab.spec import spec_util\n'), ((4764, 4793), 'slm_lab.spec.spec_util.tick', 'spec_util.tick', (['spec', '"""trial"""'], {}), "(spec, 'trial')\n", (4778, 4793), False, 'from slm_lab.spec import spec_util\n'), ((4811, 4831), 'slm_lab.experiment.control.make_agent_env', 'make_agent_env', (['spec'], {}), '(spec)\n', (4825, 4831), False, 'from slm_lab.experiment.control import make_agent_env\n'), ((1155, 1179), 'numpy.asarray', 'np.asarray', (['[1, 1, 1, 1]'], {}), '([1, 1, 1, 1])\n', (1165, 1179), True, 'import numpy as np\n'), ((1187, 1211), 'numpy.asarray', 'np.asarray', (['[2, 2, 2, 2]'], {}), '([2, 2, 2, 2])\n', (1197, 1211), True, 'import numpy as np\n'), ((1230, 1254), 'numpy.asarray', 'np.asarray', (['[2, 2, 2, 2]'], {}), '([2, 2, 2, 2])\n', (1240, 1254), True, 'import numpy as np\n'), ((1262, 1286), 'numpy.asarray', 'np.asarray', (['[3, 3, 3, 3]'], {}), '([3, 3, 3, 3])\n', (1272, 1286), True, 'import numpy as np\n'), ((1305, 1329), 'numpy.asarray', 'np.asarray', (['[3, 3, 3, 3]'], {}), '([3, 3, 3, 3])\n', (1315, 1329), True, 'import numpy as np\n'), ((1337, 1361), 'numpy.asarray', 'np.asarray', (['[4, 4, 4, 4]'], {}), '([4, 4, 4, 4])\n', (1347, 1361), True, 'import numpy as np\n'), ((1380, 1404), 'numpy.asarray', 'np.asarray', (['[4, 4, 4, 4]'], {}), '([4, 4, 4, 4])\n', (1390, 1404), True, 'import numpy as np\n'), ((1412, 1436), 'numpy.asarray', 'np.asarray', (['[5, 5, 5, 5]'], {}), '([5, 5, 5, 5])\n', (1422, 1436), True, 'import numpy as np\n'), ((1455, 1479), 'numpy.asarray', 'np.asarray', (['[5, 5, 5, 5]'], {}), '([5, 5, 5, 5])\n', (1465, 1479), True, 'import numpy as np\n'), ((1487, 1511), 'numpy.asarray', 'np.asarray', (['[6, 6, 6, 6]'], {}), '([6, 6, 6, 6])\n', (1497, 1511), True, 'import numpy as np\n'), ((1530, 1554), 'numpy.asarray', 'np.asarray', (['[6, 6, 6, 6]'], {}), '([6, 6, 6, 6])\n', (1540, 1554), True, 'import numpy as np\n'), ((1562, 1586), 'numpy.asarray', 'np.asarray', (['[7, 7, 7, 7]'], {}), '([7, 7, 7, 7])\n', (1572, 1586), True, 'import numpy as np\n'), ((1605, 1629), 'numpy.asarray', 'np.asarray', (['[7, 7, 7, 7]'], {}), '([7, 7, 7, 7])\n', (1615, 1629), True, 'import numpy as np\n'), ((1637, 1661), 'numpy.asarray', 'np.asarray', (['[8, 8, 8, 8]'], {}), '([8, 8, 8, 8])\n', (1647, 1661), True, 'import numpy as np\n'), ((1680, 1704), 'numpy.asarray', 'np.asarray', (['[8, 8, 8, 8]'], {}), '([8, 8, 8, 8])\n', (1690, 1704), True, 'import numpy as np\n'), ((1712, 1736), 'numpy.asarray', 'np.asarray', (['[9, 9, 9, 9]'], {}), '([9, 9, 9, 9])\n', (1722, 1736), True, 'import numpy as np\n'), ((2078, 2102), 'numpy.asarray', 'np.asarray', (['[1, 1, 1, 1]'], {}), '([1, 1, 1, 1])\n', (2088, 2102), True, 'import numpy as np\n'), ((2110, 2134), 'numpy.asarray', 'np.asarray', (['[2, 2, 2, 2]'], {}), '([2, 2, 2, 2])\n', (2120, 2134), True, 'import numpy as np\n'), ((2153, 2177), 'numpy.asarray', 'np.asarray', (['[2, 2, 2, 2]'], {}), '([2, 2, 2, 2])\n', (2163, 2177), True, 'import numpy as np\n'), ((2185, 2209), 'numpy.asarray', 'np.asarray', (['[3, 3, 3, 3]'], {}), '([3, 3, 3, 3])\n', (2195, 2209), True, 'import numpy as np\n'), ((2228, 2252), 'numpy.asarray', 'np.asarray', (['[3, 3, 3, 3]'], {}), '([3, 3, 3, 3])\n', (2238, 2252), True, 'import numpy as np\n'), ((2260, 2284), 'numpy.asarray', 'np.asarray', (['[4, 4, 4, 4]'], {}), '([4, 4, 4, 4])\n', (2270, 2284), True, 'import numpy as np\n'), ((2303, 2327), 'numpy.asarray', 'np.asarray', (['[4, 4, 4, 4]'], {}), '([4, 4, 4, 4])\n', (2313, 2327), True, 'import numpy as np\n'), ((2335, 2359), 'numpy.asarray', 'np.asarray', (['[5, 5, 5, 5]'], {}), '([5, 5, 5, 5])\n', (2345, 2359), True, 'import numpy as np\n'), ((2378, 2402), 'numpy.asarray', 'np.asarray', (['[5, 5, 5, 5]'], {}), '([5, 5, 5, 5])\n', (2388, 2402), True, 'import numpy as np\n'), ((2410, 2434), 'numpy.asarray', 'np.asarray', (['[6, 6, 6, 6]'], {}), '([6, 6, 6, 6])\n', (2420, 2434), True, 'import numpy as np\n'), ((2453, 2477), 'numpy.asarray', 'np.asarray', (['[6, 6, 6, 6]'], {}), '([6, 6, 6, 6])\n', (2463, 2477), True, 'import numpy as np\n'), ((2485, 2509), 'numpy.asarray', 'np.asarray', (['[7, 7, 7, 7]'], {}), '([7, 7, 7, 7])\n', (2495, 2509), True, 'import numpy as np\n'), ((2528, 2552), 'numpy.asarray', 'np.asarray', (['[7, 7, 7, 7]'], {}), '([7, 7, 7, 7])\n', (2538, 2552), True, 'import numpy as np\n'), ((2560, 2584), 'numpy.asarray', 'np.asarray', (['[8, 8, 8, 8]'], {}), '([8, 8, 8, 8])\n', (2570, 2584), True, 'import numpy as np\n'), ((2603, 2627), 'numpy.asarray', 'np.asarray', (['[8, 8, 8, 8]'], {}), '([8, 8, 8, 8])\n', (2613, 2627), True, 'import numpy as np\n'), ((2635, 2659), 'numpy.asarray', 'np.asarray', (['[9, 9, 9, 9]'], {}), '([9, 9, 9, 9])\n', (2645, 2659), True, 'import numpy as np\n'), ((3030, 3054), 'numpy.asarray', 'np.asarray', (['[1, 1, 1, 1]'], {}), '([1, 1, 1, 1])\n', (3040, 3054), True, 'import numpy as np\n'), ((3062, 3086), 'numpy.asarray', 'np.asarray', (['[2, 2, 2, 2]'], {}), '([2, 2, 2, 2])\n', (3072, 3086), True, 'import numpy as np\n'), ((3105, 3129), 'numpy.asarray', 'np.asarray', (['[2, 2, 2, 2]'], {}), '([2, 2, 2, 2])\n', (3115, 3129), True, 'import numpy as np\n'), ((3137, 3161), 'numpy.asarray', 'np.asarray', (['[3, 3, 3, 3]'], {}), '([3, 3, 3, 3])\n', (3147, 3161), True, 'import numpy as np\n'), ((3180, 3204), 'numpy.asarray', 'np.asarray', (['[3, 3, 3, 3]'], {}), '([3, 3, 3, 3])\n', (3190, 3204), True, 'import numpy as np\n'), ((3212, 3236), 'numpy.asarray', 'np.asarray', (['[4, 4, 4, 4]'], {}), '([4, 4, 4, 4])\n', (3222, 3236), True, 'import numpy as np\n'), ((3255, 3279), 'numpy.asarray', 'np.asarray', (['[4, 4, 4, 4]'], {}), '([4, 4, 4, 4])\n', (3265, 3279), True, 'import numpy as np\n'), ((3287, 3311), 'numpy.asarray', 'np.asarray', (['[5, 5, 5, 5]'], {}), '([5, 5, 5, 5])\n', (3297, 3311), True, 'import numpy as np\n'), ((3330, 3354), 'numpy.asarray', 'np.asarray', (['[5, 5, 5, 5]'], {}), '([5, 5, 5, 5])\n', (3340, 3354), True, 'import numpy as np\n'), ((3362, 3386), 'numpy.asarray', 'np.asarray', (['[6, 6, 6, 6]'], {}), '([6, 6, 6, 6])\n', (3372, 3386), True, 'import numpy as np\n'), ((3405, 3429), 'numpy.asarray', 'np.asarray', (['[6, 6, 6, 6]'], {}), '([6, 6, 6, 6])\n', (3415, 3429), True, 'import numpy as np\n'), ((3437, 3461), 'numpy.asarray', 'np.asarray', (['[7, 7, 7, 7]'], {}), '([7, 7, 7, 7])\n', (3447, 3461), True, 'import numpy as np\n'), ((3480, 3504), 'numpy.asarray', 'np.asarray', (['[7, 7, 7, 7]'], {}), '([7, 7, 7, 7])\n', (3490, 3504), True, 'import numpy as np\n'), ((3512, 3536), 'numpy.asarray', 'np.asarray', (['[8, 8, 8, 8]'], {}), '([8, 8, 8, 8])\n', (3522, 3536), True, 'import numpy as np\n'), ((3555, 3579), 'numpy.asarray', 'np.asarray', (['[8, 8, 8, 8]'], {}), '([8, 8, 8, 8])\n', (3565, 3579), True, 'import numpy as np\n'), ((3587, 3611), 'numpy.asarray', 'np.asarray', (['[9, 9, 9, 9]'], {}), '([9, 9, 9, 9])\n', (3597, 3611), True, 'import numpy as np\n'), ((3985, 4009), 'numpy.asarray', 'np.asarray', (['[1, 1, 1, 1]'], {}), '([1, 1, 1, 1])\n', (3995, 4009), True, 'import numpy as np\n'), ((4017, 4041), 'numpy.asarray', 'np.asarray', (['[2, 2, 2, 2]'], {}), '([2, 2, 2, 2])\n', (4027, 4041), True, 'import numpy as np\n'), ((4066, 4090), 'numpy.asarray', 'np.asarray', (['[2, 2, 2, 2]'], {}), '([2, 2, 2, 2])\n', (4076, 4090), True, 'import numpy as np\n'), ((4098, 4122), 'numpy.asarray', 'np.asarray', (['[3, 3, 3, 3]'], {}), '([3, 3, 3, 3])\n', (4108, 4122), True, 'import numpy as np\n'), ((4144, 4168), 'numpy.asarray', 'np.asarray', (['[3, 3, 3, 3]'], {}), '([3, 3, 3, 3])\n', (4154, 4168), True, 'import numpy as np\n'), ((4176, 4200), 'numpy.asarray', 'np.asarray', (['[4, 4, 4, 4]'], {}), '([4, 4, 4, 4])\n', (4186, 4200), True, 'import numpy as np\n'), ((4222, 4246), 'numpy.asarray', 'np.asarray', (['[4, 4, 4, 4]'], {}), '([4, 4, 4, 4])\n', (4232, 4246), True, 'import numpy as np\n'), ((4254, 4278), 'numpy.asarray', 'np.asarray', (['[5, 5, 5, 5]'], {}), '([5, 5, 5, 5])\n', (4264, 4278), True, 'import numpy as np\n'), ((4300, 4324), 'numpy.asarray', 'np.asarray', (['[5, 5, 5, 5]'], {}), '([5, 5, 5, 5])\n', (4310, 4324), True, 'import numpy as np\n'), ((4332, 4356), 'numpy.asarray', 'np.asarray', (['[6, 6, 6, 6]'], {}), '([6, 6, 6, 6])\n', (4342, 4356), True, 'import numpy as np\n'), ((4381, 4405), 'numpy.asarray', 'np.asarray', (['[6, 6, 6, 6]'], {}), '([6, 6, 6, 6])\n', (4391, 4405), True, 'import numpy as np\n'), ((4413, 4437), 'numpy.asarray', 'np.asarray', (['[7, 7, 7, 7]'], {}), '([7, 7, 7, 7])\n', (4423, 4437), True, 'import numpy as np\n'), ((4459, 4483), 'numpy.asarray', 'np.asarray', (['[7, 7, 7, 7]'], {}), '([7, 7, 7, 7])\n', (4469, 4483), True, 'import numpy as np\n'), ((4491, 4515), 'numpy.asarray', 'np.asarray', (['[8, 8, 8, 8]'], {}), '([8, 8, 8, 8])\n', (4501, 4515), True, 'import numpy as np\n'), ((4537, 4561), 'numpy.asarray', 'np.asarray', (['[8, 8, 8, 8]'], {}), '([8, 8, 8, 8])\n', (4547, 4561), True, 'import numpy as np\n'), ((4569, 4593), 'numpy.asarray', 'np.asarray', (['[9, 9, 9, 9]'], {}), '([9, 9, 9, 9])\n', (4579, 4593), True, 'import numpy as np\n')] |
from mmdet.apis import init_detector, inference_detector, show_result_pyplot, show_result
import mmcv
import cv2
import numpy as np
import torch
import os
import time
def bboxSelect(result, select_cls, CLASSES, score_thr=0.3):
if isinstance(result, tuple):
bbox_result, segm_result = result
else:
bbox_result, segm_result = result, None
bboxes = np.vstack(bbox_result)# draw bounding boxes
# print(bboxes)
labels = [
np.full(bbox.shape[0], i, dtype=np.int32)
for i, bbox in enumerate(bbox_result)
]
labels = np.concatenate(labels)
# print(labels)
if score_thr > 0:
assert bboxes.shape[1] == 5
scores = bboxes[:, -1]
inds = scores > score_thr
bboxes = bboxes[inds, :]
# print(bboxes)
labels = labels[inds]
# print(labels)
labels_select = np.full(labels.shape[0], select_cls)
inds_l = (labels == labels_select)
bboxes = bboxes[inds_l, :]
# print(bboxes)
labels = labels[inds_l]
# print(labels)
return bboxes, labels
# config_file = '../configs/faster_rcnn_r50_fpn_1x.py'
# # download the checkpoint from model zoo and put it in `checkpoints/`
# checkpoint_file = '../work_dirs/faster_rcnn_r50_fpn_1x/epoch_12.pth'
config_file = '../configs/pascal_voc/ssd300_mobilenetv2_voc_1.py'
# download the checkpoint from model zoo and put it in `checkpoints/`
checkpoint_file = '../work_dirs/ssd300_mobilenet_v2_helmet_2/latest.pth'
# build the model from a config file and a checkpoint file
model = init_detector(config_file, checkpoint_file, device='cuda:0')
# img_path = '../demo/demo.jpg'
image_dir = r"/media/gzzn/WITAI/Dataset/COCO/COCO_baby/JPEGImages_person"
image_list_txt = r"/media/gzzn/WITAI/Dataset/COCO/COCO_baby/name_list_person/have_person_name_part.txt"
image_list = open(image_list_txt).readlines()
txt_save_dir = r"/media/gzzn/WITAI/Dataset/COCO/COCO_baby/none_hat"
CLASSES = ('person', 'blue', 'white', 'yellow', 'red', 'none', 'light_jacket', 'red_life_jacket')
if not os.path.exists(txt_save_dir):
os.mkdir(txt_save_dir)
for image_name in image_list:
image_name = image_name.strip()
image_path = os.path.join(image_dir, image_name+'.jpg')
# video_name_idx = os.path.splitext(video_name)[0].split('_')
# video_class = "%s_%s_%s_%s"%(video_name_idx[1], video_name_idx[2], video_name_idx[3], video_name_idx[4])
txt_name = image_name + ".txt"
txt_path = os.path.join(txt_save_dir, txt_name)
txt_w = open(txt_path, 'w')
image = cv2.imread(image_path)
result = inference_detector(model, image)
bboxes, labels = bboxSelect(result, 5, model.CLASSES, 0.5)
image_draw = image
for idx, label in enumerate(labels):
bbox = bboxes[idx, :-1]
# img_crop = rotate90_img[int(bbox[1]):int(bbox[3]), int(bbox[0]):int(bbox[2])]
image_draw = cv2.rectangle(image_draw, (int(bbox[0]), int(bbox[1])), (int(bbox[2]), int(bbox[3])), (0,255,0), 2)
person_line = "none %d %d %d %d\n" % (int(bbox[0]), int(bbox[1]), int(bbox[2]), int(bbox[3])) # video_name_idx[0]
txt_w.write(person_line)
image_draw = cv2.putText(image_draw, CLASSES[label], (int(bbox[0]), int(bbox[1])), cv2.FONT_HERSHEY_SIMPLEX, 1.2,
(0,255,0))
# cv2.imwrite(frame_save_path, img_crop)
txt_w.close()
cv2.imshow('image_draw', image_draw)
if cv2.waitKey(2) & 0xFF == ord('q'): # ?q???
break
cv2.destroyAllWindows()
| [
"numpy.full",
"os.mkdir",
"cv2.waitKey",
"mmdet.apis.init_detector",
"os.path.exists",
"mmdet.apis.inference_detector",
"cv2.imshow",
"cv2.imread",
"numpy.vstack",
"cv2.destroyAllWindows",
"os.path.join",
"numpy.concatenate"
] | [((1569, 1629), 'mmdet.apis.init_detector', 'init_detector', (['config_file', 'checkpoint_file'], {'device': '"""cuda:0"""'}), "(config_file, checkpoint_file, device='cuda:0')\n", (1582, 1629), False, 'from mmdet.apis import init_detector, inference_detector, show_result_pyplot, show_result\n'), ((3486, 3509), 'cv2.destroyAllWindows', 'cv2.destroyAllWindows', ([], {}), '()\n', (3507, 3509), False, 'import cv2\n'), ((375, 397), 'numpy.vstack', 'np.vstack', (['bbox_result'], {}), '(bbox_result)\n', (384, 397), True, 'import numpy as np\n'), ((569, 591), 'numpy.concatenate', 'np.concatenate', (['labels'], {}), '(labels)\n', (583, 591), True, 'import numpy as np\n'), ((2062, 2090), 'os.path.exists', 'os.path.exists', (['txt_save_dir'], {}), '(txt_save_dir)\n', (2076, 2090), False, 'import os\n'), ((2096, 2118), 'os.mkdir', 'os.mkdir', (['txt_save_dir'], {}), '(txt_save_dir)\n', (2104, 2118), False, 'import os\n'), ((2202, 2246), 'os.path.join', 'os.path.join', (['image_dir', "(image_name + '.jpg')"], {}), "(image_dir, image_name + '.jpg')\n", (2214, 2246), False, 'import os\n'), ((2472, 2508), 'os.path.join', 'os.path.join', (['txt_save_dir', 'txt_name'], {}), '(txt_save_dir, txt_name)\n', (2484, 2508), False, 'import os\n'), ((2553, 2575), 'cv2.imread', 'cv2.imread', (['image_path'], {}), '(image_path)\n', (2563, 2575), False, 'import cv2\n'), ((2589, 2621), 'mmdet.apis.inference_detector', 'inference_detector', (['model', 'image'], {}), '(model, image)\n', (2607, 2621), False, 'from mmdet.apis import init_detector, inference_detector, show_result_pyplot, show_result\n'), ((3383, 3419), 'cv2.imshow', 'cv2.imshow', (['"""image_draw"""', 'image_draw'], {}), "('image_draw', image_draw)\n", (3393, 3419), False, 'import cv2\n'), ((462, 503), 'numpy.full', 'np.full', (['bbox.shape[0]', 'i'], {'dtype': 'np.int32'}), '(bbox.shape[0], i, dtype=np.int32)\n', (469, 503), True, 'import numpy as np\n'), ((870, 906), 'numpy.full', 'np.full', (['labels.shape[0]', 'select_cls'], {}), '(labels.shape[0], select_cls)\n', (877, 906), True, 'import numpy as np\n'), ((3427, 3441), 'cv2.waitKey', 'cv2.waitKey', (['(2)'], {}), '(2)\n', (3438, 3441), False, 'import cv2\n')] |
import itertools
import numpy as np
import tensorflow as tf
import video_prediction as vp
from video_prediction import ops
from video_prediction.models import VideoPredictionModel, SAVPVideoPredictionModel
from video_prediction.models import pix2pix_model, mocogan_model, spectral_norm_model
from video_prediction.models.savp_model import create_encoder, apply_kernels, apply_flows, identity_kernel
from video_prediction.ops import dense, conv2d, flatten, tile_concat
from video_prediction.rnn_ops import BasicConv2DLSTMCell, Conv2DGRUCell
from video_prediction.utils import tf_utils
# Amount to use when lower bounding tensors
RELU_SHIFT = 1e-12
def encoder_fn(inputs, hparams=None):
image_pairs = []
for i in range(hparams.num_views):
suffix = '%d' % i if i > 0 else ''
images = inputs['images' + suffix]
image_pairs.append(images[:hparams.sequence_length - 1])
image_pairs.append(images[1:hparams.sequence_length])
image_pairs = tf.concat(image_pairs, axis=-1)
if 'actions' in inputs:
image_pairs = tile_concat([image_pairs,
tf.expand_dims(tf.expand_dims(inputs['actions'], axis=-2), axis=-2)], axis=-1)
outputs = create_encoder(image_pairs,
e_net=hparams.e_net,
use_e_rnn=hparams.use_e_rnn,
rnn=hparams.rnn,
nz=hparams.nz,
nef=hparams.nef,
n_layers=hparams.n_layers,
norm_layer=hparams.norm_layer)
return outputs
def discriminator_fn(targets, inputs=None, hparams=None):
outputs = {}
if hparams.gan_weight or hparams.vae_gan_weight:
_, pix2pix_outputs = pix2pix_model.discriminator_fn(targets, inputs=inputs, hparams=hparams)
outputs.update(pix2pix_outputs)
if hparams.image_gan_weight or hparams.image_vae_gan_weight or \
hparams.video_gan_weight or hparams.video_vae_gan_weight or \
hparams.acvideo_gan_weight or hparams.acvideo_vae_gan_weight:
_, mocogan_outputs = mocogan_model.discriminator_fn(targets, inputs=inputs, hparams=hparams)
outputs.update(mocogan_outputs)
if hparams.image_sn_gan_weight or hparams.image_sn_vae_gan_weight or \
hparams.video_sn_gan_weight or hparams.video_sn_vae_gan_weight:
_, spectral_norm_outputs = spectral_norm_model.discriminator_fn(targets, inputs=inputs, hparams=hparams)
outputs.update(spectral_norm_outputs)
return None, outputs
class DNACell(tf.nn.rnn_cell.RNNCell):
def __init__(self, inputs, hparams, reuse=None):
super(DNACell, self).__init__(_reuse=reuse)
self.inputs = inputs
self.hparams = hparams
if self.hparams.where_add not in ('input', 'all', 'middle'):
raise ValueError('Invalid where_add %s' % self.hparams.where_add)
batch_size = inputs['images'].shape[1].value
image_shape = inputs['images'].shape.as_list()[2:]
height, width, _ = image_shape
scale_size = max(height, width)
if scale_size == 256:
self.encoder_layer_specs = [
(self.hparams.ngf, False),
(self.hparams.ngf * 2, False),
(self.hparams.ngf * 4, True),
(self.hparams.ngf * 8, True),
(self.hparams.ngf * 8, True),
]
self.decoder_layer_specs = [
(self.hparams.ngf * 8, True),
(self.hparams.ngf * 4, True),
(self.hparams.ngf * 2, False),
(self.hparams.ngf, False),
(self.hparams.ngf, False),
]
elif scale_size == 64:
self.encoder_layer_specs = [
(self.hparams.ngf, True),
(self.hparams.ngf * 2, True),
(self.hparams.ngf * 4, True),
]
self.decoder_layer_specs = [
(self.hparams.ngf * 2, True),
(self.hparams.ngf, True),
(self.hparams.ngf, False),
]
elif scale_size == 32:
self.encoder_layer_specs = [
(self.hparams.ngf, True),
(self.hparams.ngf * 2, True),
]
self.decoder_layer_specs = [
(self.hparams.ngf, True),
(self.hparams.ngf, False),
]
else:
raise NotImplementedError
# output_size
num_masks = self.hparams.last_frames * self.hparams.num_transformed_images + \
int(bool(self.hparams.prev_image_background)) + \
int(bool(self.hparams.first_image_background and not self.hparams.context_images_background)) + \
(self.hparams.context_frames if self.hparams.context_images_background else 0) + \
int(bool(self.hparams.generate_scratch_image))
output_size = {}
for i in range(self.hparams.num_views):
suffix = '%d' % i if i > 0 else ''
output_size['gen_images' + suffix] = tf.TensorShape(image_shape)
output_size['transformed_images' + suffix] = tf.TensorShape(image_shape + [num_masks])
output_size['masks' + suffix] = tf.TensorShape([height, width, 1, num_masks])
if 'pix_distribs' in inputs:
for i in range(self.hparams.num_views):
suffix = '%d' % i if i > 0 else ''
num_motions = inputs['pix_distribs' + suffix].shape[-1].value
output_size['gen_pix_distribs' + suffix] = tf.TensorShape([height, width, num_motions])
output_size['transformed_pix_distribs' + suffix] = tf.TensorShape([height, width, num_motions, num_masks])
if 'states' in inputs:
output_size['gen_states'] = inputs['states'].shape[2:]
if self.hparams.transformation == 'flow':
for i in range(self.hparams.num_views):
suffix = '%d' % i if i > 0 else ''
output_size['gen_flows' + suffix] = tf.TensorShape([height, width, 2, self.hparams.last_frames * self.hparams.num_transformed_images])
output_size['gen_flows_rgb' + suffix] = tf.TensorShape([height, width, 3, self.hparams.last_frames * self.hparams.num_transformed_images])
self._output_size = output_size
# state_size
conv_rnn_state_sizes = []
conv_rnn_height, conv_rnn_width = height, width
for out_channels, use_conv_rnn in self.encoder_layer_specs:
conv_rnn_height //= 2
conv_rnn_width //= 2
if use_conv_rnn:
conv_rnn_state_sizes.append(tf.TensorShape([conv_rnn_height, conv_rnn_width, out_channels]))
for out_channels, use_conv_rnn in self.decoder_layer_specs:
conv_rnn_height *= 2
conv_rnn_width *= 2
if use_conv_rnn:
conv_rnn_state_sizes.append(tf.TensorShape([conv_rnn_height, conv_rnn_width, out_channels]))
if self.hparams.conv_rnn == 'lstm':
conv_rnn_state_sizes = [tf.nn.rnn_cell.LSTMStateTuple(conv_rnn_state_size, conv_rnn_state_size)
for conv_rnn_state_size in conv_rnn_state_sizes]
state_size = {'time': tf.TensorShape([])}
for i in range(self.hparams.num_views):
suffix = '%d' % i if i > 0 else ''
state_size['gen_image' + suffix] = tf.TensorShape(image_shape)
state_size['last_images' + suffix] = [tf.TensorShape(image_shape)] * self.hparams.last_frames
for i in range(self.hparams.num_views):
suffix = '%d' % i if i > 0 else ''
state_size['conv_rnn_states' + suffix] = conv_rnn_state_sizes
if self.hparams.shared_views:
break
if 'zs' in inputs and self.hparams.use_rnn_z:
rnn_z_state_size = tf.TensorShape([self.hparams.nz])
if self.hparams.rnn == 'lstm':
rnn_z_state_size = tf.nn.rnn_cell.LSTMStateTuple(rnn_z_state_size, rnn_z_state_size)
state_size['rnn_z_state'] = rnn_z_state_size
if 'pix_distribs' in inputs:
for i in range(self.hparams.num_views):
suffix = '%d' % i if i > 0 else ''
state_size['gen_pix_distrib' + suffix] = tf.TensorShape([height, width, num_motions])
state_size['last_pix_distribs' + suffix] = [tf.TensorShape([height, width, num_motions])] * self.hparams.last_frames
if 'states' in inputs:
state_size['gen_state'] = inputs['states'].shape[2:]
self._state_size = state_size
ground_truth_sampling_shape = [self.hparams.sequence_length - 1 - self.hparams.context_frames, batch_size]
if self.hparams.schedule_sampling == 'none':
ground_truth_sampling = tf.constant(False, dtype=tf.bool, shape=ground_truth_sampling_shape)
elif self.hparams.schedule_sampling in ('inverse_sigmoid', 'linear'):
if self.hparams.schedule_sampling == 'inverse_sigmoid':
k = self.hparams.schedule_sampling_k
start_step = self.hparams.schedule_sampling_steps[0]
iter_num = tf.to_float(tf.train.get_or_create_global_step())
prob = (k / (k + tf.exp((iter_num - start_step) / k)))
prob = tf.cond(tf.less(iter_num, start_step), lambda: 1.0, lambda: prob)
elif self.hparams.schedule_sampling == 'linear':
start_step, end_step = self.hparams.schedule_sampling_steps
step = tf.clip_by_value(tf.train.get_or_create_global_step(), start_step, end_step)
prob = 1.0 - tf.to_float(step - start_step) / tf.to_float(end_step - start_step)
log_probs = tf.log([1 - prob, prob])
ground_truth_sampling = tf.multinomial([log_probs] * batch_size, ground_truth_sampling_shape[0])
ground_truth_sampling = tf.cast(tf.transpose(ground_truth_sampling, [1, 0]), dtype=tf.bool)
# Ensure that eventually, the model is deterministically
# autoregressive (as opposed to autoregressive with very high probability).
ground_truth_sampling = tf.cond(tf.less(prob, 0.001),
lambda: tf.constant(False, dtype=tf.bool, shape=ground_truth_sampling_shape),
lambda: ground_truth_sampling)
else:
raise NotImplementedError
ground_truth_context = tf.constant(True, dtype=tf.bool, shape=[self.hparams.context_frames, batch_size])
self.ground_truth = tf.concat([ground_truth_context, ground_truth_sampling], axis=0)
@property
def output_size(self):
return self._output_size
@property
def state_size(self):
return self._state_size
def zero_state(self, batch_size, dtype):
init_state = super(DNACell, self).zero_state(batch_size, dtype)
for i in range(self.hparams.num_views):
suffix = '%d' % i if i > 0 else ''
init_state['last_images' + suffix] = [self.inputs['images' + suffix][0]] * self.hparams.last_frames
if 'pix_distribs' in self.inputs:
init_state['last_pix_distribs' + suffix] = [self.inputs['pix_distribs' + suffix][0]] * self.hparams.last_frames
return init_state
def _rnn_func(self, inputs, state, num_units):
if self.hparams.rnn == 'lstm':
RNNCell = tf.contrib.rnn.BasicLSTMCell
elif self.hparams.rnn == 'gru':
RNNCell = tf.contrib.rnn.GRUCell
else:
raise NotImplementedError
rnn_cell = RNNCell(num_units, reuse=tf.get_variable_scope().reuse)
return rnn_cell(inputs, state)
def _conv_rnn_func(self, inputs, state, filters):
inputs_shape = inputs.get_shape().as_list()
input_shape = inputs_shape[1:]
if self.hparams.norm_layer == 'none':
normalizer_fn = None
else:
normalizer_fn = ops.get_norm_layer(self.hparams.norm_layer)
if self.hparams.conv_rnn == 'lstm':
Conv2DRNNCell = BasicConv2DLSTMCell
elif self.hparams.conv_rnn == 'gru':
Conv2DRNNCell = Conv2DGRUCell
else:
raise NotImplementedError
if self.hparams.ablation_conv_rnn_norm:
conv_rnn_cell = Conv2DRNNCell(input_shape, filters, kernel_size=(5, 5),
reuse=tf.get_variable_scope().reuse)
h, state = conv_rnn_cell(inputs, state)
outputs = (normalizer_fn(h), state)
else:
conv_rnn_cell = Conv2DRNNCell(input_shape, filters, kernel_size=(5, 5),
normalizer_fn=normalizer_fn,
separate_norms=self.hparams.norm_layer == 'layer',
reuse=tf.get_variable_scope().reuse)
outputs = conv_rnn_cell(inputs, state)
return outputs
def call(self, inputs, states):
norm_layer = ops.get_norm_layer(self.hparams.norm_layer)
downsample_layer = ops.get_downsample_layer(self.hparams.downsample_layer)
upsample_layer = ops.get_upsample_layer(self.hparams.upsample_layer)
image_shape = inputs['images'].get_shape().as_list()
batch_size, height, width, color_channels = image_shape
time = states['time']
with tf.control_dependencies([tf.assert_equal(time[1:], time[0])]):
t = tf.to_int32(tf.identity(time[0]))
if 'states' in inputs:
state = tf.where(self.ground_truth[t], inputs['states'], states['gen_state'])
state_action = []
state_action_z = []
if 'actions' in inputs:
state_action.append(inputs['actions'])
state_action_z.append(inputs['actions'])
if 'states' in inputs:
state_action.append(state)
# don't backpropagate the convnet through the state dynamics
state_action_z.append(tf.stop_gradient(state))
if 'zs' in inputs:
if self.hparams.use_rnn_z:
with tf.variable_scope('%s_z' % self.hparams.rnn):
rnn_z, rnn_z_state = self._rnn_func(inputs['zs'], states['rnn_z_state'], self.hparams.nz)
state_action_z.append(rnn_z)
else:
state_action_z.append(inputs['zs'])
def concat(tensors, axis):
if len(tensors) == 0:
return tf.zeros([batch_size, 0])
elif len(tensors) == 1:
return tensors[0]
else:
return tf.concat(tensors, axis=axis)
state_action = concat(state_action, axis=-1)
state_action_z = concat(state_action_z, axis=-1)
image_views = []
first_image_views = []
if 'pix_distribs' in inputs:
pix_distrib_views = []
for i in range(self.hparams.num_views):
suffix = '%d' % i if i > 0 else ''
image_view = tf.where(self.ground_truth[t], inputs['images' + suffix], states['gen_image' + suffix]) # schedule sampling (if any)
image_views.append(image_view)
first_image_views.append(self.inputs['images' + suffix][0])
if 'pix_distribs' in inputs:
pix_distrib_view = tf.where(self.ground_truth[t], inputs['pix_distribs' + suffix], states['gen_pix_distrib' + suffix])
pix_distrib_views.append(pix_distrib_view)
outputs = {}
new_states = {}
all_layers = []
for i in range(self.hparams.num_views):
suffix = '%d' % i if i > 0 else ''
conv_rnn_states = states['conv_rnn_states' + suffix]
layers = []
new_conv_rnn_states = []
for i, (out_channels, use_conv_rnn) in enumerate(self.encoder_layer_specs):
with tf.variable_scope('h%d' % i + suffix):
if i == 0:
# all image views and the first image corresponding to this view only
h = tf.concat(image_views + first_image_views, axis=-1)
kernel_size = (5, 5)
else:
h = layers[-1][-1]
kernel_size = (3, 3)
if self.hparams.where_add == 'all' or (self.hparams.where_add == 'input' and i == 0):
h = tile_concat([h, state_action_z[:, None, None, :]], axis=-1)
h = downsample_layer(h, out_channels, kernel_size=kernel_size, strides=(2, 2))
h = norm_layer(h)
h = tf.nn.relu(h)
if use_conv_rnn:
conv_rnn_state = conv_rnn_states[len(new_conv_rnn_states)]
with tf.variable_scope('%s_h%d' % (self.hparams.conv_rnn, i) + suffix):
if self.hparams.where_add == 'all':
conv_rnn_h = tile_concat([h, state_action_z[:, None, None, :]], axis=-1)
else:
conv_rnn_h = h
conv_rnn_h, conv_rnn_state = self._conv_rnn_func(conv_rnn_h, conv_rnn_state, out_channels)
new_conv_rnn_states.append(conv_rnn_state)
layers.append((h, conv_rnn_h) if use_conv_rnn else (h,))
num_encoder_layers = len(layers)
for i, (out_channels, use_conv_rnn) in enumerate(self.decoder_layer_specs):
with tf.variable_scope('h%d' % len(layers) + suffix):
if i == 0:
h = layers[-1][-1]
else:
h = tf.concat([layers[-1][-1], layers[num_encoder_layers - i - 1][-1]], axis=-1)
if self.hparams.where_add == 'all' or (self.hparams.where_add == 'middle' and i == 0):
h = tile_concat([h, state_action_z[:, None, None, :]], axis=-1)
h = upsample_layer(h, out_channels, kernel_size=(3, 3), strides=(2, 2))
h = norm_layer(h)
h = tf.nn.relu(h)
if use_conv_rnn:
conv_rnn_state = conv_rnn_states[len(new_conv_rnn_states)]
with tf.variable_scope('%s_h%d' % (self.hparams.conv_rnn, len(layers)) + suffix):
if self.hparams.where_add == 'all':
conv_rnn_h = tile_concat([h, state_action_z[:, None, None, :]], axis=-1)
else:
conv_rnn_h = h
conv_rnn_h, conv_rnn_state = self._conv_rnn_func(conv_rnn_h, conv_rnn_state, out_channels)
new_conv_rnn_states.append(conv_rnn_state)
layers.append((h, conv_rnn_h) if use_conv_rnn else (h,))
assert len(new_conv_rnn_states) == len(conv_rnn_states)
new_states['conv_rnn_states' + suffix] = new_conv_rnn_states
all_layers.append(layers)
if self.hparams.shared_views:
break
for i in range(self.hparams.num_views):
suffix = '%d' % i if i > 0 else ''
if self.hparams.shared_views:
layers, = all_layers
else:
layers = all_layers[i]
image = image_views[i]
last_images = states['last_images' + suffix][1:] + [image]
if 'pix_distribs' in inputs:
pix_distrib = pix_distrib_views[i]
last_pix_distribs = states['last_pix_distribs' + suffix][1:] + [pix_distrib]
if self.hparams.last_frames and self.hparams.num_transformed_images:
if self.hparams.transformation == 'flow':
with tf.variable_scope('h%d_flow' % len(layers) + suffix):
h_flow = conv2d(layers[-1][-1], self.hparams.ngf, kernel_size=(3, 3), strides=(1, 1))
h_flow = norm_layer(h_flow)
h_flow = tf.nn.relu(h_flow)
with tf.variable_scope('flows' + suffix):
flows = conv2d(h_flow, 2 * self.hparams.last_frames * self.hparams.num_transformed_images, kernel_size=(3, 3), strides=(1, 1))
flows = tf.reshape(flows, [batch_size, height, width, 2, self.hparams.last_frames * self.hparams.num_transformed_images])
else:
assert len(self.hparams.kernel_size) == 2
kernel_shape = list(self.hparams.kernel_size) + [self.hparams.last_frames * self.hparams.num_transformed_images]
if self.hparams.transformation == 'dna':
with tf.variable_scope('h%d_dna_kernel' % len(layers) + suffix):
h_dna_kernel = conv2d(layers[-1][-1], self.hparams.ngf, kernel_size=(3, 3), strides=(1, 1))
h_dna_kernel = norm_layer(h_dna_kernel)
h_dna_kernel = tf.nn.relu(h_dna_kernel)
# Using largest hidden state for predicting untied conv kernels.
with tf.variable_scope('dna_kernels' + suffix):
kernels = conv2d(h_dna_kernel, np.prod(kernel_shape), kernel_size=(3, 3), strides=(1, 1))
kernels = tf.reshape(kernels, [batch_size, height, width] + kernel_shape)
kernels = kernels + identity_kernel(self.hparams.kernel_size)[None, None, None, :, :, None]
kernel_spatial_axes = [3, 4]
elif self.hparams.transformation == 'cdna':
with tf.variable_scope('cdna_kernels' + suffix):
smallest_layer = layers[num_encoder_layers - 1][-1]
kernels = dense(flatten(smallest_layer), np.prod(kernel_shape))
kernels = tf.reshape(kernels, [batch_size] + kernel_shape)
kernels = kernels + identity_kernel(self.hparams.kernel_size)[None, :, :, None]
kernel_spatial_axes = [1, 2]
else:
raise ValueError('Invalid transformation %s' % self.hparams.transformation)
if self.hparams.transformation != 'flow':
with tf.name_scope('kernel_normalization' + suffix):
kernels = tf.nn.relu(kernels - RELU_SHIFT) + RELU_SHIFT
kernels /= tf.reduce_sum(kernels, axis=kernel_spatial_axes, keepdims=True)
if self.hparams.generate_scratch_image:
with tf.variable_scope('h%d_scratch' % len(layers) + suffix):
h_scratch = conv2d(layers[-1][-1], self.hparams.ngf, kernel_size=(3, 3), strides=(1, 1))
h_scratch = norm_layer(h_scratch)
h_scratch = tf.nn.relu(h_scratch)
# Using largest hidden state for predicting a new image layer.
# This allows the network to also generate one image from scratch,
# which is useful when regions of the image become unoccluded.
with tf.variable_scope('scratch_image' + suffix):
scratch_image = conv2d(h_scratch, color_channels, kernel_size=(3, 3), strides=(1, 1))
scratch_image = tf.nn.sigmoid(scratch_image)
with tf.name_scope('transformed_images' + suffix):
transformed_images = []
if self.hparams.last_frames and self.hparams.num_transformed_images:
if self.hparams.transformation == 'flow':
transformed_images.extend(apply_flows(last_images, flows))
else:
transformed_images.extend(apply_kernels(last_images, kernels, self.hparams.dilation_rate))
if self.hparams.prev_image_background:
transformed_images.append(image)
if self.hparams.first_image_background and not self.hparams.context_images_background:
transformed_images.append(self.inputs['images' + suffix][0])
if self.hparams.context_images_background:
transformed_images.extend(tf.unstack(self.inputs['images' + suffix][:self.hparams.context_frames]))
if self.hparams.generate_scratch_image:
transformed_images.append(scratch_image)
if 'pix_distribs' in inputs:
with tf.name_scope('transformed_pix_distribs' + suffix):
transformed_pix_distribs = []
if self.hparams.last_frames and self.hparams.num_transformed_images:
if self.hparams.transformation == 'flow':
transformed_pix_distribs.extend(apply_flows(last_pix_distribs, flows))
else:
transformed_pix_distribs.extend(apply_kernels(last_pix_distribs, kernels, self.hparams.dilation_rate))
if self.hparams.prev_image_background:
transformed_pix_distribs.append(pix_distrib)
if self.hparams.first_image_background and not self.hparams.context_images_background:
transformed_pix_distribs.append(self.inputs['pix_distribs' + suffix][0])
if self.hparams.context_images_background:
transformed_pix_distribs.extend(tf.unstack(self.inputs['pix_distribs' + suffix][:self.hparams.context_frames]))
if self.hparams.generate_scratch_image:
transformed_pix_distribs.append(pix_distrib)
with tf.name_scope('masks' + suffix):
if len(transformed_images) > 1:
with tf.variable_scope('h%d_masks' % len(layers) + suffix):
h_masks = conv2d(layers[-1][-1], self.hparams.ngf, kernel_size=(3, 3), strides=(1, 1))
h_masks = norm_layer(h_masks)
h_masks = tf.nn.relu(h_masks)
with tf.variable_scope('masks' + suffix):
if self.hparams.dependent_mask:
h_masks = tf.concat([h_masks] + transformed_images, axis=-1)
masks = conv2d(h_masks, len(transformed_images), kernel_size=(3, 3), strides=(1, 1))
masks = tf.nn.softmax(masks)
masks = tf.split(masks, len(transformed_images), axis=-1)
elif len(transformed_images) == 1:
masks = [tf.ones([batch_size, height, width, 1])]
else:
raise ValueError("Either one of the following should be true: "
"last_frames and num_transformed_images, first_image_background, "
"prev_image_background, generate_scratch_image")
with tf.name_scope('gen_images' + suffix):
assert len(transformed_images) == len(masks)
gen_image = tf.add_n([transformed_image * mask
for transformed_image, mask in zip(transformed_images, masks)])
if 'pix_distribs' in inputs:
with tf.name_scope('gen_pix_distribs' + suffix):
assert len(transformed_pix_distribs) == len(masks)
gen_pix_distrib = tf.add_n([transformed_pix_distrib * mask
for transformed_pix_distrib, mask in zip(transformed_pix_distribs, masks)])
if self.hparams.renormalize_pixdistrib:
gen_pix_distrib /= tf.reduce_sum(gen_pix_distrib, axis=(1, 2), keepdims=True)
outputs['gen_images' + suffix] = gen_image
outputs['transformed_images' + suffix] = tf.stack(transformed_images, axis=-1)
outputs['masks' + suffix] = tf.stack(masks, axis=-1)
if 'pix_distribs' in inputs:
outputs['gen_pix_distribs' + suffix] = gen_pix_distrib
outputs['transformed_pix_distribs' + suffix] = tf.stack(transformed_pix_distribs, axis=-1)
if self.hparams.transformation == 'flow':
outputs['gen_flows' + suffix] = flows
flows_transposed = tf.transpose(flows, [0, 1, 2, 4, 3])
flows_rgb_transposed = tf_utils.flow_to_rgb(flows_transposed)
flows_rgb = tf.transpose(flows_rgb_transposed, [0, 1, 2, 4, 3])
outputs['gen_flows_rgb' + suffix] = flows_rgb
new_states['gen_image' + suffix] = gen_image
new_states['last_images' + suffix] = last_images
if 'pix_distribs' in inputs:
new_states['gen_pix_distrib' + suffix] = gen_pix_distrib
new_states['last_pix_distribs' + suffix] = last_pix_distribs
if 'states' in inputs:
with tf.name_scope('gen_states'):
with tf.variable_scope('state_pred'):
gen_state = dense(state_action, inputs['states'].shape[-1].value)
if 'states' in inputs:
outputs['gen_states'] = gen_state
new_states['time'] = time + 1
if 'zs' in inputs and self.hparams.use_rnn_z:
new_states['rnn_z_state'] = rnn_z_state
if 'states' in inputs:
new_states['gen_state'] = gen_state
return outputs, new_states
def generator_fn(inputs, outputs_enc=None, hparams=None):
batch_size = inputs['images'].shape[1].value
inputs = {name: tf_utils.maybe_pad_or_slice(input, hparams.sequence_length - 1)
for name, input in inputs.items()}
if hparams.nz:
def sample_zs():
if outputs_enc is None:
zs = tf.random_normal([hparams.sequence_length - 1, batch_size, hparams.nz], 0, 1)
else:
enc_zs_mu = outputs_enc['enc_zs_mu']
enc_zs_log_sigma_sq = outputs_enc['enc_zs_log_sigma_sq']
eps = tf.random_normal([hparams.sequence_length - 1, batch_size, hparams.nz], 0, 1)
zs = enc_zs_mu + tf.sqrt(tf.exp(enc_zs_log_sigma_sq)) * eps
return zs
inputs['zs'] = sample_zs()
else:
if outputs_enc is not None:
raise ValueError('outputs_enc has to be None when nz is 0.')
cell = DNACell(inputs, hparams)
outputs, _ = tf.nn.dynamic_rnn(cell, inputs, dtype=tf.float32,
swap_memory=False, time_major=True)
if hparams.nz:
inputs_samples = {name: flatten(tf.tile(input[:, None], [1, hparams.num_samples] + [1] * (input.shape.ndims - 1)), 1, 2)
for name, input in inputs.items() if name != 'zs'}
inputs_samples['zs'] = tf.concat([sample_zs() for _ in range(hparams.num_samples)], axis=1)
with tf.variable_scope(tf.get_variable_scope(), reuse=True):
cell_samples = DNACell(inputs_samples, hparams)
outputs_samples, _ = tf.nn.dynamic_rnn(cell_samples, inputs_samples, dtype=tf.float32,
swap_memory=False, time_major=True)
for i in range(hparams.num_views):
suffix = '%d' % i if i > 0 else ''
gen_images_samples = outputs_samples['gen_images' + suffix]
gen_images_samples = tf.stack(tf.split(gen_images_samples, hparams.num_samples, axis=1), axis=-1)
gen_images_samples_avg = tf.reduce_mean(gen_images_samples, axis=-1)
outputs['gen_images_samples' + suffix] = gen_images_samples
outputs['gen_images_samples_avg' + suffix] = gen_images_samples_avg
# the RNN outputs generated images from time step 1 to sequence_length,
# but generator_fn should only return images past context_frames
outputs = {name: output[hparams.context_frames - 1:] for name, output in outputs.items()}
gen_images = outputs['gen_images']
outputs['ground_truth_sampling_mean'] = tf.reduce_mean(tf.to_float(cell.ground_truth[hparams.context_frames:]))
return gen_images, outputs
class MultiSAVPVideoPredictionModel(SAVPVideoPredictionModel):
def __init__(self, *args, **kwargs):
VideoPredictionModel.__init__(self,
generator_fn, discriminator_fn, encoder_fn, *args, **kwargs)
if self.hparams.e_net == 'none' or self.hparams.nz == 0:
self.encoder_fn = None
if self.hparams.d_net == 'none':
self.discriminator_fn = None
self.deterministic = not self.hparams.nz
def get_default_hparams_dict(self):
default_hparams = super(MultiSAVPVideoPredictionModel, self).get_default_hparams_dict()
hparams = dict(
num_views=1,
shared_views=False,
)
return dict(itertools.chain(default_hparams.items(), hparams.items()))
def generator_loss_fn(self, inputs, outputs, targets):
gen_losses = super(MultiSAVPVideoPredictionModel, self).generator_loss_fn(inputs, outputs, targets)
hparams = self.hparams
# TODO: support for other losses of the other views
for i in range(1, hparams.num_views): # skip i = 0 since it should have already been done by the superclass
suffix = '%d' % i if i > 0 else ''
if hparams.l1_weight or hparams.l2_weight:
gen_images = outputs.get('gen_images%s_enc' % suffix, outputs['gen_images' + suffix])
target_images = inputs['images' + suffix][self.hparams.context_frames:]
if hparams.l1_weight:
gen_l1_loss = vp.losses.l1_loss(gen_images, target_images)
gen_losses["gen_l1_loss" + suffix] = (gen_l1_loss, hparams.l1_weight)
if hparams.l2_weight:
gen_l2_loss = vp.losses.l2_loss(gen_images, target_images)
gen_losses["gen_l2_loss" + suffix] = (gen_l2_loss, hparams.l2_weight)
if (hparams.l1_weight or hparams.l2_weight) and hparams.num_scales > 1:
raise NotImplementedError
if hparams.tv_weight:
gen_flows = outputs.get('gen_flows%s_enc' % suffix, outputs['gen_flows' + suffix])
flow_diff1 = gen_flows[..., 1:, :, :, :] - gen_flows[..., :-1, :, :, :]
flow_diff2 = gen_flows[..., :, 1:, :, :] - gen_flows[..., :, :-1, :, :]
# sum over the multiple transformations but take the mean for the other dimensions
gen_tv_loss = tf.reduce_mean(tf.reduce_sum(tf.abs(flow_diff1), axis=(-2, -1))) + \
tf.reduce_mean(tf.reduce_sum(tf.abs(flow_diff2), axis=(-2, -1)))
gen_losses['gen_tv_loss' + suffix] = (gen_tv_loss, hparams.tv_weight)
return gen_losses
| [
"tensorflow.reduce_sum",
"tensorflow.nn.rnn_cell.LSTMStateTuple",
"tensorflow.identity",
"tensorflow.get_variable_scope",
"tensorflow.reshape",
"video_prediction.ops.flatten",
"video_prediction.utils.tf_utils.flow_to_rgb",
"video_prediction.models.VideoPredictionModel.__init__",
"video_prediction.mo... | [((981, 1012), 'tensorflow.concat', 'tf.concat', (['image_pairs'], {'axis': '(-1)'}), '(image_pairs, axis=-1)\n', (990, 1012), True, 'import tensorflow as tf\n'), ((1217, 1411), 'video_prediction.models.savp_model.create_encoder', 'create_encoder', (['image_pairs'], {'e_net': 'hparams.e_net', 'use_e_rnn': 'hparams.use_e_rnn', 'rnn': 'hparams.rnn', 'nz': 'hparams.nz', 'nef': 'hparams.nef', 'n_layers': 'hparams.n_layers', 'norm_layer': 'hparams.norm_layer'}), '(image_pairs, e_net=hparams.e_net, use_e_rnn=hparams.\n use_e_rnn, rnn=hparams.rnn, nz=hparams.nz, nef=hparams.nef, n_layers=\n hparams.n_layers, norm_layer=hparams.norm_layer)\n', (1231, 1411), False, 'from video_prediction.models.savp_model import create_encoder, apply_kernels, apply_flows, identity_kernel\n'), ((30491, 30580), 'tensorflow.nn.dynamic_rnn', 'tf.nn.dynamic_rnn', (['cell', 'inputs'], {'dtype': 'tf.float32', 'swap_memory': '(False)', 'time_major': '(True)'}), '(cell, inputs, dtype=tf.float32, swap_memory=False,\n time_major=True)\n', (30508, 30580), True, 'import tensorflow as tf\n'), ((1783, 1854), 'video_prediction.models.pix2pix_model.discriminator_fn', 'pix2pix_model.discriminator_fn', (['targets'], {'inputs': 'inputs', 'hparams': 'hparams'}), '(targets, inputs=inputs, hparams=hparams)\n', (1813, 1854), False, 'from video_prediction.models import pix2pix_model, mocogan_model, spectral_norm_model\n'), ((2141, 2212), 'video_prediction.models.mocogan_model.discriminator_fn', 'mocogan_model.discriminator_fn', (['targets'], {'inputs': 'inputs', 'hparams': 'hparams'}), '(targets, inputs=inputs, hparams=hparams)\n', (2171, 2212), False, 'from video_prediction.models import pix2pix_model, mocogan_model, spectral_norm_model\n'), ((2439, 2516), 'video_prediction.models.spectral_norm_model.discriminator_fn', 'spectral_norm_model.discriminator_fn', (['targets'], {'inputs': 'inputs', 'hparams': 'hparams'}), '(targets, inputs=inputs, hparams=hparams)\n', (2475, 2516), False, 'from video_prediction.models import pix2pix_model, mocogan_model, spectral_norm_model\n'), ((10522, 10607), 'tensorflow.constant', 'tf.constant', (['(True)'], {'dtype': 'tf.bool', 'shape': '[self.hparams.context_frames, batch_size]'}), '(True, dtype=tf.bool, shape=[self.hparams.context_frames,\n batch_size])\n', (10533, 10607), True, 'import tensorflow as tf\n'), ((10632, 10696), 'tensorflow.concat', 'tf.concat', (['[ground_truth_context, ground_truth_sampling]'], {'axis': '(0)'}), '([ground_truth_context, ground_truth_sampling], axis=0)\n', (10641, 10696), True, 'import tensorflow as tf\n'), ((13089, 13132), 'video_prediction.ops.get_norm_layer', 'ops.get_norm_layer', (['self.hparams.norm_layer'], {}), '(self.hparams.norm_layer)\n', (13107, 13132), False, 'from video_prediction import ops\n'), ((13160, 13215), 'video_prediction.ops.get_downsample_layer', 'ops.get_downsample_layer', (['self.hparams.downsample_layer'], {}), '(self.hparams.downsample_layer)\n', (13184, 13215), False, 'from video_prediction import ops\n'), ((13241, 13292), 'video_prediction.ops.get_upsample_layer', 'ops.get_upsample_layer', (['self.hparams.upsample_layer'], {}), '(self.hparams.upsample_layer)\n', (13263, 13292), False, 'from video_prediction import ops\n'), ((29650, 29713), 'video_prediction.utils.tf_utils.maybe_pad_or_slice', 'tf_utils.maybe_pad_or_slice', (['input', '(hparams.sequence_length - 1)'], {}), '(input, hparams.sequence_length - 1)\n', (29677, 29713), False, 'from video_prediction.utils import tf_utils\n'), ((32094, 32149), 'tensorflow.to_float', 'tf.to_float', (['cell.ground_truth[hparams.context_frames:]'], {}), '(cell.ground_truth[hparams.context_frames:])\n', (32105, 32149), True, 'import tensorflow as tf\n'), ((32296, 32396), 'video_prediction.models.VideoPredictionModel.__init__', 'VideoPredictionModel.__init__', (['self', 'generator_fn', 'discriminator_fn', 'encoder_fn', '*args'], {}), '(self, generator_fn, discriminator_fn,\n encoder_fn, *args, **kwargs)\n', (32325, 32396), False, 'from video_prediction.models import VideoPredictionModel, SAVPVideoPredictionModel\n'), ((5104, 5131), 'tensorflow.TensorShape', 'tf.TensorShape', (['image_shape'], {}), '(image_shape)\n', (5118, 5131), True, 'import tensorflow as tf\n'), ((5189, 5230), 'tensorflow.TensorShape', 'tf.TensorShape', (['(image_shape + [num_masks])'], {}), '(image_shape + [num_masks])\n', (5203, 5230), True, 'import tensorflow as tf\n'), ((5275, 5320), 'tensorflow.TensorShape', 'tf.TensorShape', (['[height, width, 1, num_masks]'], {}), '([height, width, 1, num_masks])\n', (5289, 5320), True, 'import tensorflow as tf\n'), ((7286, 7304), 'tensorflow.TensorShape', 'tf.TensorShape', (['[]'], {}), '([])\n', (7300, 7304), True, 'import tensorflow as tf\n'), ((7448, 7475), 'tensorflow.TensorShape', 'tf.TensorShape', (['image_shape'], {}), '(image_shape)\n', (7462, 7475), True, 'import tensorflow as tf\n'), ((7900, 7933), 'tensorflow.TensorShape', 'tf.TensorShape', (['[self.hparams.nz]'], {}), '([self.hparams.nz])\n', (7914, 7933), True, 'import tensorflow as tf\n'), ((8849, 8917), 'tensorflow.constant', 'tf.constant', (['(False)'], {'dtype': 'tf.bool', 'shape': 'ground_truth_sampling_shape'}), '(False, dtype=tf.bool, shape=ground_truth_sampling_shape)\n', (8860, 8917), True, 'import tensorflow as tf\n'), ((12030, 12073), 'video_prediction.ops.get_norm_layer', 'ops.get_norm_layer', (['self.hparams.norm_layer'], {}), '(self.hparams.norm_layer)\n', (12048, 12073), False, 'from video_prediction import ops\n'), ((13627, 13696), 'tensorflow.where', 'tf.where', (['self.ground_truth[t]', "inputs['states']", "states['gen_state']"], {}), "(self.ground_truth[t], inputs['states'], states['gen_state'])\n", (13635, 13696), True, 'import tensorflow as tf\n'), ((15068, 15160), 'tensorflow.where', 'tf.where', (['self.ground_truth[t]', "inputs['images' + suffix]", "states['gen_image' + suffix]"], {}), "(self.ground_truth[t], inputs['images' + suffix], states[\n 'gen_image' + suffix])\n", (15076, 15160), True, 'import tensorflow as tf\n'), ((27934, 27971), 'tensorflow.stack', 'tf.stack', (['transformed_images'], {'axis': '(-1)'}), '(transformed_images, axis=-1)\n', (27942, 27971), True, 'import tensorflow as tf\n'), ((28012, 28036), 'tensorflow.stack', 'tf.stack', (['masks'], {'axis': '(-1)'}), '(masks, axis=-1)\n', (28020, 28036), True, 'import tensorflow as tf\n'), ((31099, 31204), 'tensorflow.nn.dynamic_rnn', 'tf.nn.dynamic_rnn', (['cell_samples', 'inputs_samples'], {'dtype': 'tf.float32', 'swap_memory': '(False)', 'time_major': '(True)'}), '(cell_samples, inputs_samples, dtype=tf.float32,\n swap_memory=False, time_major=True)\n', (31116, 31204), True, 'import tensorflow as tf\n'), ((31561, 31604), 'tensorflow.reduce_mean', 'tf.reduce_mean', (['gen_images_samples'], {'axis': '(-1)'}), '(gen_images_samples, axis=-1)\n', (31575, 31604), True, 'import tensorflow as tf\n'), ((5598, 5642), 'tensorflow.TensorShape', 'tf.TensorShape', (['[height, width, num_motions]'], {}), '([height, width, num_motions])\n', (5612, 5642), True, 'import tensorflow as tf\n'), ((5710, 5765), 'tensorflow.TensorShape', 'tf.TensorShape', (['[height, width, num_motions, num_masks]'], {}), '([height, width, num_motions, num_masks])\n', (5724, 5765), True, 'import tensorflow as tf\n'), ((6069, 6172), 'tensorflow.TensorShape', 'tf.TensorShape', (['[height, width, 2, self.hparams.last_frames * self.hparams.\n num_transformed_images]'], {}), '([height, width, 2, self.hparams.last_frames * self.hparams.\n num_transformed_images])\n', (6083, 6172), True, 'import tensorflow as tf\n'), ((6224, 6327), 'tensorflow.TensorShape', 'tf.TensorShape', (['[height, width, 3, self.hparams.last_frames * self.hparams.\n num_transformed_images]'], {}), '([height, width, 3, self.hparams.last_frames * self.hparams.\n num_transformed_images])\n', (6238, 6327), True, 'import tensorflow as tf\n'), ((7099, 7170), 'tensorflow.nn.rnn_cell.LSTMStateTuple', 'tf.nn.rnn_cell.LSTMStateTuple', (['conv_rnn_state_size', 'conv_rnn_state_size'], {}), '(conv_rnn_state_size, conv_rnn_state_size)\n', (7128, 7170), True, 'import tensorflow as tf\n'), ((8012, 8077), 'tensorflow.nn.rnn_cell.LSTMStateTuple', 'tf.nn.rnn_cell.LSTMStateTuple', (['rnn_z_state_size', 'rnn_z_state_size'], {}), '(rnn_z_state_size, rnn_z_state_size)\n', (8041, 8077), True, 'import tensorflow as tf\n'), ((8332, 8376), 'tensorflow.TensorShape', 'tf.TensorShape', (['[height, width, num_motions]'], {}), '([height, width, num_motions])\n', (8346, 8376), True, 'import tensorflow as tf\n'), ((9781, 9805), 'tensorflow.log', 'tf.log', (['[1 - prob, prob]'], {}), '([1 - prob, prob])\n', (9787, 9805), True, 'import tensorflow as tf\n'), ((9842, 9914), 'tensorflow.multinomial', 'tf.multinomial', (['([log_probs] * batch_size)', 'ground_truth_sampling_shape[0]'], {}), '([log_probs] * batch_size, ground_truth_sampling_shape[0])\n', (9856, 9914), True, 'import tensorflow as tf\n'), ((13553, 13573), 'tensorflow.identity', 'tf.identity', (['time[0]'], {}), '(time[0])\n', (13564, 13573), True, 'import tensorflow as tf\n'), ((14065, 14088), 'tensorflow.stop_gradient', 'tf.stop_gradient', (['state'], {}), '(state)\n', (14081, 14088), True, 'import tensorflow as tf\n'), ((14542, 14567), 'tensorflow.zeros', 'tf.zeros', (['[batch_size, 0]'], {}), '([batch_size, 0])\n', (14550, 14567), True, 'import tensorflow as tf\n'), ((15377, 15481), 'tensorflow.where', 'tf.where', (['self.ground_truth[t]', "inputs['pix_distribs' + suffix]", "states['gen_pix_distrib' + suffix]"], {}), "(self.ground_truth[t], inputs['pix_distribs' + suffix], states[\n 'gen_pix_distrib' + suffix])\n", (15385, 15481), True, 'import tensorflow as tf\n'), ((23447, 23491), 'tensorflow.name_scope', 'tf.name_scope', (["('transformed_images' + suffix)"], {}), "('transformed_images' + suffix)\n", (23460, 23491), True, 'import tensorflow as tf\n'), ((25750, 25781), 'tensorflow.name_scope', 'tf.name_scope', (["('masks' + suffix)"], {}), "('masks' + suffix)\n", (25763, 25781), True, 'import tensorflow as tf\n'), ((27017, 27053), 'tensorflow.name_scope', 'tf.name_scope', (["('gen_images' + suffix)"], {}), "('gen_images' + suffix)\n", (27030, 27053), True, 'import tensorflow as tf\n'), ((28212, 28255), 'tensorflow.stack', 'tf.stack', (['transformed_pix_distribs'], {'axis': '(-1)'}), '(transformed_pix_distribs, axis=-1)\n', (28220, 28255), True, 'import tensorflow as tf\n'), ((28399, 28435), 'tensorflow.transpose', 'tf.transpose', (['flows', '[0, 1, 2, 4, 3]'], {}), '(flows, [0, 1, 2, 4, 3])\n', (28411, 28435), True, 'import tensorflow as tf\n'), ((28475, 28513), 'video_prediction.utils.tf_utils.flow_to_rgb', 'tf_utils.flow_to_rgb', (['flows_transposed'], {}), '(flows_transposed)\n', (28495, 28513), False, 'from video_prediction.utils import tf_utils\n'), ((28542, 28593), 'tensorflow.transpose', 'tf.transpose', (['flows_rgb_transposed', '[0, 1, 2, 4, 3]'], {}), '(flows_rgb_transposed, [0, 1, 2, 4, 3])\n', (28554, 28593), True, 'import tensorflow as tf\n'), ((29015, 29042), 'tensorflow.name_scope', 'tf.name_scope', (['"""gen_states"""'], {}), "('gen_states')\n", (29028, 29042), True, 'import tensorflow as tf\n'), ((29864, 29941), 'tensorflow.random_normal', 'tf.random_normal', (['[hparams.sequence_length - 1, batch_size, hparams.nz]', '(0)', '(1)'], {}), '([hparams.sequence_length - 1, batch_size, hparams.nz], 0, 1)\n', (29880, 29941), True, 'import tensorflow as tf\n'), ((30108, 30185), 'tensorflow.random_normal', 'tf.random_normal', (['[hparams.sequence_length - 1, batch_size, hparams.nz]', '(0)', '(1)'], {}), '([hparams.sequence_length - 1, batch_size, hparams.nz], 0, 1)\n', (30124, 30185), True, 'import tensorflow as tf\n'), ((30671, 30756), 'tensorflow.tile', 'tf.tile', (['input[:, None]', '([1, hparams.num_samples] + [1] * (input.shape.ndims - 1))'], {}), '(input[:, None], [1, hparams.num_samples] + [1] * (input.shape.ndims -\n 1))\n', (30678, 30756), True, 'import tensorflow as tf\n'), ((30968, 30991), 'tensorflow.get_variable_scope', 'tf.get_variable_scope', ([], {}), '()\n', (30989, 30991), True, 'import tensorflow as tf\n'), ((31456, 31513), 'tensorflow.split', 'tf.split', (['gen_images_samples', 'hparams.num_samples'], {'axis': '(1)'}), '(gen_images_samples, hparams.num_samples, axis=1)\n', (31464, 31513), True, 'import tensorflow as tf\n'), ((33675, 33719), 'video_prediction.losses.l1_loss', 'vp.losses.l1_loss', (['gen_images', 'target_images'], {}), '(gen_images, target_images)\n', (33692, 33719), True, 'import video_prediction as vp\n'), ((33870, 33914), 'video_prediction.losses.l2_loss', 'vp.losses.l2_loss', (['gen_images', 'target_images'], {}), '(gen_images, target_images)\n', (33887, 33914), True, 'import video_prediction as vp\n'), ((1139, 1181), 'tensorflow.expand_dims', 'tf.expand_dims', (["inputs['actions']"], {'axis': '(-2)'}), "(inputs['actions'], axis=-2)\n", (1153, 1181), True, 'import tensorflow as tf\n'), ((6683, 6746), 'tensorflow.TensorShape', 'tf.TensorShape', (['[conv_rnn_height, conv_rnn_width, out_channels]'], {}), '([conv_rnn_height, conv_rnn_width, out_channels])\n', (6697, 6746), True, 'import tensorflow as tf\n'), ((6954, 7017), 'tensorflow.TensorShape', 'tf.TensorShape', (['[conv_rnn_height, conv_rnn_width, out_channels]'], {}), '([conv_rnn_height, conv_rnn_width, out_channels])\n', (6968, 7017), True, 'import tensorflow as tf\n'), ((7526, 7553), 'tensorflow.TensorShape', 'tf.TensorShape', (['image_shape'], {}), '(image_shape)\n', (7540, 7553), True, 'import tensorflow as tf\n'), ((9959, 10002), 'tensorflow.transpose', 'tf.transpose', (['ground_truth_sampling', '[1, 0]'], {}), '(ground_truth_sampling, [1, 0])\n', (9971, 10002), True, 'import tensorflow as tf\n'), ((10220, 10240), 'tensorflow.less', 'tf.less', (['prob', '(0.001)'], {}), '(prob, 0.001)\n', (10227, 10240), True, 'import tensorflow as tf\n'), ((11693, 11716), 'tensorflow.get_variable_scope', 'tf.get_variable_scope', ([], {}), '()\n', (11714, 11716), True, 'import tensorflow as tf\n'), ((13487, 13521), 'tensorflow.assert_equal', 'tf.assert_equal', (['time[1:]', 'time[0]'], {}), '(time[1:], time[0])\n', (13502, 13521), True, 'import tensorflow as tf\n'), ((14178, 14222), 'tensorflow.variable_scope', 'tf.variable_scope', (["('%s_z' % self.hparams.rnn)"], {}), "('%s_z' % self.hparams.rnn)\n", (14195, 14222), True, 'import tensorflow as tf\n'), ((14679, 14708), 'tensorflow.concat', 'tf.concat', (['tensors'], {'axis': 'axis'}), '(tensors, axis=axis)\n', (14688, 14708), True, 'import tensorflow as tf\n'), ((15936, 15973), 'tensorflow.variable_scope', 'tf.variable_scope', (["('h%d' % i + suffix)"], {}), "('h%d' % i + suffix)\n", (15953, 15973), True, 'import tensorflow as tf\n'), ((16694, 16707), 'tensorflow.nn.relu', 'tf.nn.relu', (['h'], {}), '(h)\n', (16704, 16707), True, 'import tensorflow as tf\n'), ((18155, 18168), 'tensorflow.nn.relu', 'tf.nn.relu', (['h'], {}), '(h)\n', (18165, 18168), True, 'import tensorflow as tf\n'), ((22765, 22841), 'video_prediction.ops.conv2d', 'conv2d', (['layers[-1][-1]', 'self.hparams.ngf'], {'kernel_size': '(3, 3)', 'strides': '(1, 1)'}), '(layers[-1][-1], self.hparams.ngf, kernel_size=(3, 3), strides=(1, 1))\n', (22771, 22841), False, 'from video_prediction.ops import dense, conv2d, flatten, tile_concat\n'), ((22928, 22949), 'tensorflow.nn.relu', 'tf.nn.relu', (['h_scratch'], {}), '(h_scratch)\n', (22938, 22949), True, 'import tensorflow as tf\n'), ((23213, 23256), 'tensorflow.variable_scope', 'tf.variable_scope', (["('scratch_image' + suffix)"], {}), "('scratch_image' + suffix)\n", (23230, 23256), True, 'import tensorflow as tf\n'), ((23294, 23363), 'video_prediction.ops.conv2d', 'conv2d', (['h_scratch', 'color_channels'], {'kernel_size': '(3, 3)', 'strides': '(1, 1)'}), '(h_scratch, color_channels, kernel_size=(3, 3), strides=(1, 1))\n', (23300, 23363), False, 'from video_prediction.ops import dense, conv2d, flatten, tile_concat\n'), ((23400, 23428), 'tensorflow.nn.sigmoid', 'tf.nn.sigmoid', (['scratch_image'], {}), '(scratch_image)\n', (23413, 23428), True, 'import tensorflow as tf\n'), ((24555, 24605), 'tensorflow.name_scope', 'tf.name_scope', (["('transformed_pix_distribs' + suffix)"], {}), "('transformed_pix_distribs' + suffix)\n", (24568, 24605), True, 'import tensorflow as tf\n'), ((27344, 27386), 'tensorflow.name_scope', 'tf.name_scope', (["('gen_pix_distribs' + suffix)"], {}), "('gen_pix_distribs' + suffix)\n", (27357, 27386), True, 'import tensorflow as tf\n'), ((29065, 29096), 'tensorflow.variable_scope', 'tf.variable_scope', (['"""state_pred"""'], {}), "('state_pred')\n", (29082, 29096), True, 'import tensorflow as tf\n'), ((29130, 29183), 'video_prediction.ops.dense', 'dense', (['state_action', "inputs['states'].shape[-1].value"], {}), "(state_action, inputs['states'].shape[-1].value)\n", (29135, 29183), False, 'from video_prediction.ops import dense, conv2d, flatten, tile_concat\n'), ((8437, 8481), 'tensorflow.TensorShape', 'tf.TensorShape', (['[height, width, num_motions]'], {}), '([height, width, num_motions])\n', (8451, 8481), True, 'import tensorflow as tf\n'), ((9225, 9261), 'tensorflow.train.get_or_create_global_step', 'tf.train.get_or_create_global_step', ([], {}), '()\n', (9259, 9261), True, 'import tensorflow as tf\n'), ((9365, 9394), 'tensorflow.less', 'tf.less', (['iter_num', 'start_step'], {}), '(iter_num, start_step)\n', (9372, 9394), True, 'import tensorflow as tf\n'), ((10294, 10362), 'tensorflow.constant', 'tf.constant', (['(False)'], {'dtype': 'tf.bool', 'shape': 'ground_truth_sampling_shape'}), '(False, dtype=tf.bool, shape=ground_truth_sampling_shape)\n', (10305, 10362), True, 'import tensorflow as tf\n'), ((12485, 12508), 'tensorflow.get_variable_scope', 'tf.get_variable_scope', ([], {}), '()\n', (12506, 12508), True, 'import tensorflow as tf\n'), ((12926, 12949), 'tensorflow.get_variable_scope', 'tf.get_variable_scope', ([], {}), '()\n', (12947, 12949), True, 'import tensorflow as tf\n'), ((16128, 16179), 'tensorflow.concat', 'tf.concat', (['(image_views + first_image_views)'], {'axis': '(-1)'}), '(image_views + first_image_views, axis=-1)\n', (16137, 16179), True, 'import tensorflow as tf\n'), ((16473, 16532), 'video_prediction.ops.tile_concat', 'tile_concat', (['[h, state_action_z[:, None, None, :]]'], {'axis': '(-1)'}), '([h, state_action_z[:, None, None, :]], axis=-1)\n', (16484, 16532), False, 'from video_prediction.ops import dense, conv2d, flatten, tile_concat\n'), ((16845, 16910), 'tensorflow.variable_scope', 'tf.variable_scope', (["('%s_h%d' % (self.hparams.conv_rnn, i) + suffix)"], {}), "('%s_h%d' % (self.hparams.conv_rnn, i) + suffix)\n", (16862, 16910), True, 'import tensorflow as tf\n'), ((17729, 17805), 'tensorflow.concat', 'tf.concat', (['[layers[-1][-1], layers[num_encoder_layers - i - 1][-1]]'], {'axis': '(-1)'}), '([layers[-1][-1], layers[num_encoder_layers - i - 1][-1]], axis=-1)\n', (17738, 17805), True, 'import tensorflow as tf\n'), ((17941, 18000), 'video_prediction.ops.tile_concat', 'tile_concat', (['[h, state_action_z[:, None, None, :]]'], {'axis': '(-1)'}), '([h, state_action_z[:, None, None, :]], axis=-1)\n', (17952, 18000), False, 'from video_prediction.ops import dense, conv2d, flatten, tile_concat\n'), ((19889, 19965), 'video_prediction.ops.conv2d', 'conv2d', (['layers[-1][-1]', 'self.hparams.ngf'], {'kernel_size': '(3, 3)', 'strides': '(1, 1)'}), '(layers[-1][-1], self.hparams.ngf, kernel_size=(3, 3), strides=(1, 1))\n', (19895, 19965), False, 'from video_prediction.ops import dense, conv2d, flatten, tile_concat\n'), ((20051, 20069), 'tensorflow.nn.relu', 'tf.nn.relu', (['h_flow'], {}), '(h_flow)\n', (20061, 20069), True, 'import tensorflow as tf\n'), ((20096, 20131), 'tensorflow.variable_scope', 'tf.variable_scope', (["('flows' + suffix)"], {}), "('flows' + suffix)\n", (20113, 20131), True, 'import tensorflow as tf\n'), ((20165, 20288), 'video_prediction.ops.conv2d', 'conv2d', (['h_flow', '(2 * self.hparams.last_frames * self.hparams.num_transformed_images)'], {'kernel_size': '(3, 3)', 'strides': '(1, 1)'}), '(h_flow, 2 * self.hparams.last_frames * self.hparams.\n num_transformed_images, kernel_size=(3, 3), strides=(1, 1))\n', (20171, 20288), False, 'from video_prediction.ops import dense, conv2d, flatten, tile_concat\n'), ((20316, 20433), 'tensorflow.reshape', 'tf.reshape', (['flows', '[batch_size, height, width, 2, self.hparams.last_frames * self.hparams.\n num_transformed_images]'], {}), '(flows, [batch_size, height, width, 2, self.hparams.last_frames *\n self.hparams.num_transformed_images])\n', (20326, 20433), True, 'import tensorflow as tf\n'), ((22375, 22421), 'tensorflow.name_scope', 'tf.name_scope', (["('kernel_normalization' + suffix)"], {}), "('kernel_normalization' + suffix)\n", (22388, 22421), True, 'import tensorflow as tf\n'), ((22538, 22601), 'tensorflow.reduce_sum', 'tf.reduce_sum', (['kernels'], {'axis': 'kernel_spatial_axes', 'keepdims': '(True)'}), '(kernels, axis=kernel_spatial_axes, keepdims=True)\n', (22551, 22601), True, 'import tensorflow as tf\n'), ((24301, 24373), 'tensorflow.unstack', 'tf.unstack', (["self.inputs['images' + suffix][:self.hparams.context_frames]"], {}), "(self.inputs['images' + suffix][:self.hparams.context_frames])\n", (24311, 24373), True, 'import tensorflow as tf\n'), ((25945, 26021), 'video_prediction.ops.conv2d', 'conv2d', (['layers[-1][-1]', 'self.hparams.ngf'], {'kernel_size': '(3, 3)', 'strides': '(1, 1)'}), '(layers[-1][-1], self.hparams.ngf, kernel_size=(3, 3), strides=(1, 1))\n', (25951, 26021), False, 'from video_prediction.ops import dense, conv2d, flatten, tile_concat\n'), ((26110, 26129), 'tensorflow.nn.relu', 'tf.nn.relu', (['h_masks'], {}), '(h_masks)\n', (26120, 26129), True, 'import tensorflow as tf\n'), ((26156, 26191), 'tensorflow.variable_scope', 'tf.variable_scope', (["('masks' + suffix)"], {}), "('masks' + suffix)\n", (26173, 26191), True, 'import tensorflow as tf\n'), ((26479, 26499), 'tensorflow.nn.softmax', 'tf.nn.softmax', (['masks'], {}), '(masks)\n', (26492, 26499), True, 'import tensorflow as tf\n'), ((27766, 27824), 'tensorflow.reduce_sum', 'tf.reduce_sum', (['gen_pix_distrib'], {'axis': '(1, 2)', 'keepdims': '(True)'}), '(gen_pix_distrib, axis=(1, 2), keepdims=True)\n', (27779, 27824), True, 'import tensorflow as tf\n'), ((9296, 9331), 'tensorflow.exp', 'tf.exp', (['((iter_num - start_step) / k)'], {}), '((iter_num - start_step) / k)\n', (9302, 9331), True, 'import tensorflow as tf\n'), ((9600, 9636), 'tensorflow.train.get_or_create_global_step', 'tf.train.get_or_create_global_step', ([], {}), '()\n', (9634, 9636), True, 'import tensorflow as tf\n'), ((17013, 17072), 'video_prediction.ops.tile_concat', 'tile_concat', (['[h, state_action_z[:, None, None, :]]'], {'axis': '(-1)'}), '([h, state_action_z[:, None, None, :]], axis=-1)\n', (17024, 17072), False, 'from video_prediction.ops import dense, conv2d, flatten, tile_concat\n'), ((18484, 18543), 'video_prediction.ops.tile_concat', 'tile_concat', (['[h, state_action_z[:, None, None, :]]'], {'axis': '(-1)'}), '([h, state_action_z[:, None, None, :]], axis=-1)\n', (18495, 18543), False, 'from video_prediction.ops import dense, conv2d, flatten, tile_concat\n'), ((20840, 20916), 'video_prediction.ops.conv2d', 'conv2d', (['layers[-1][-1]', 'self.hparams.ngf'], {'kernel_size': '(3, 3)', 'strides': '(1, 1)'}), '(layers[-1][-1], self.hparams.ngf, kernel_size=(3, 3), strides=(1, 1))\n', (20846, 20916), False, 'from video_prediction.ops import dense, conv2d, flatten, tile_concat\n'), ((21028, 21052), 'tensorflow.nn.relu', 'tf.nn.relu', (['h_dna_kernel'], {}), '(h_dna_kernel)\n', (21038, 21052), True, 'import tensorflow as tf\n'), ((21172, 21213), 'tensorflow.variable_scope', 'tf.variable_scope', (["('dna_kernels' + suffix)"], {}), "('dna_kernels' + suffix)\n", (21189, 21213), True, 'import tensorflow as tf\n'), ((21371, 21434), 'tensorflow.reshape', 'tf.reshape', (['kernels', '([batch_size, height, width] + kernel_shape)'], {}), '(kernels, [batch_size, height, width] + kernel_shape)\n', (21381, 21434), True, 'import tensorflow as tf\n'), ((22457, 22489), 'tensorflow.nn.relu', 'tf.nn.relu', (['(kernels - RELU_SHIFT)'], {}), '(kernels - RELU_SHIFT)\n', (22467, 22489), True, 'import tensorflow as tf\n'), ((23730, 23761), 'video_prediction.models.savp_model.apply_flows', 'apply_flows', (['last_images', 'flows'], {}), '(last_images, flows)\n', (23741, 23761), False, 'from video_prediction.models.savp_model import create_encoder, apply_kernels, apply_flows, identity_kernel\n'), ((23839, 23902), 'video_prediction.models.savp_model.apply_kernels', 'apply_kernels', (['last_images', 'kernels', 'self.hparams.dilation_rate'], {}), '(last_images, kernels, self.hparams.dilation_rate)\n', (23852, 23902), False, 'from video_prediction.models.savp_model import create_encoder, apply_kernels, apply_flows, identity_kernel\n'), ((25523, 25601), 'tensorflow.unstack', 'tf.unstack', (["self.inputs['pix_distribs' + suffix][:self.hparams.context_frames]"], {}), "(self.inputs['pix_distribs' + suffix][:self.hparams.context_frames])\n", (25533, 25601), True, 'import tensorflow as tf\n'), ((26287, 26337), 'tensorflow.concat', 'tf.concat', (['([h_masks] + transformed_images)'], {'axis': '(-1)'}), '([h_masks] + transformed_images, axis=-1)\n', (26296, 26337), True, 'import tensorflow as tf\n'), ((26662, 26701), 'tensorflow.ones', 'tf.ones', (['[batch_size, height, width, 1]'], {}), '([batch_size, height, width, 1])\n', (26669, 26701), True, 'import tensorflow as tf\n'), ((30227, 30254), 'tensorflow.exp', 'tf.exp', (['enc_zs_log_sigma_sq'], {}), '(enc_zs_log_sigma_sq)\n', (30233, 30254), True, 'import tensorflow as tf\n'), ((34594, 34612), 'tensorflow.abs', 'tf.abs', (['flow_diff1'], {}), '(flow_diff1)\n', (34600, 34612), True, 'import tensorflow as tf\n'), ((34693, 34711), 'tensorflow.abs', 'tf.abs', (['flow_diff2'], {}), '(flow_diff2)\n', (34699, 34711), True, 'import tensorflow as tf\n'), ((9689, 9719), 'tensorflow.to_float', 'tf.to_float', (['(step - start_step)'], {}), '(step - start_step)\n', (9700, 9719), True, 'import tensorflow as tf\n'), ((9722, 9756), 'tensorflow.to_float', 'tf.to_float', (['(end_step - start_step)'], {}), '(end_step - start_step)\n', (9733, 9756), True, 'import tensorflow as tf\n'), ((21274, 21295), 'numpy.prod', 'np.prod', (['kernel_shape'], {}), '(kernel_shape)\n', (21281, 21295), True, 'import numpy as np\n'), ((21701, 21743), 'tensorflow.variable_scope', 'tf.variable_scope', (["('cdna_kernels' + suffix)"], {}), "('cdna_kernels' + suffix)\n", (21718, 21743), True, 'import tensorflow as tf\n'), ((21955, 22003), 'tensorflow.reshape', 'tf.reshape', (['kernels', '([batch_size] + kernel_shape)'], {}), '(kernels, [batch_size] + kernel_shape)\n', (21965, 22003), True, 'import tensorflow as tf\n'), ((24872, 24909), 'video_prediction.models.savp_model.apply_flows', 'apply_flows', (['last_pix_distribs', 'flows'], {}), '(last_pix_distribs, flows)\n', (24883, 24909), False, 'from video_prediction.models.savp_model import create_encoder, apply_kernels, apply_flows, identity_kernel\n'), ((25001, 25070), 'video_prediction.models.savp_model.apply_kernels', 'apply_kernels', (['last_pix_distribs', 'kernels', 'self.hparams.dilation_rate'], {}), '(last_pix_distribs, kernels, self.hparams.dilation_rate)\n', (25014, 25070), False, 'from video_prediction.models.savp_model import create_encoder, apply_kernels, apply_flows, identity_kernel\n'), ((21483, 21524), 'video_prediction.models.savp_model.identity_kernel', 'identity_kernel', (['self.hparams.kernel_size'], {}), '(self.hparams.kernel_size)\n', (21498, 21524), False, 'from video_prediction.models.savp_model import create_encoder, apply_kernels, apply_flows, identity_kernel\n'), ((21869, 21892), 'video_prediction.ops.flatten', 'flatten', (['smallest_layer'], {}), '(smallest_layer)\n', (21876, 21892), False, 'from video_prediction.ops import dense, conv2d, flatten, tile_concat\n'), ((21894, 21915), 'numpy.prod', 'np.prod', (['kernel_shape'], {}), '(kernel_shape)\n', (21901, 21915), True, 'import numpy as np\n'), ((22052, 22093), 'video_prediction.models.savp_model.identity_kernel', 'identity_kernel', (['self.hparams.kernel_size'], {}), '(self.hparams.kernel_size)\n', (22067, 22093), False, 'from video_prediction.models.savp_model import create_encoder, apply_kernels, apply_flows, identity_kernel\n')] |
r"""
Solve Poisson equation in 2D with homogeneous Dirichlet bcs in one direction and
periodic in the other. The domain is (-inf, inf) x [0, 2pi]
.. math::
\nabla^2 u = f,
The equation to solve for a Hermite x Fourier basis is
.. math::
(\nabla u, \nabla v) = -(f, v)
"""
import os
import sys
from sympy import symbols, exp, hermite, cos
import numpy as np
from shenfun import inner, grad, TestFunction, TrialFunction, la, \
Array, Function, FunctionSpace, TensorProductSpace, comm
assert len(sys.argv) == 2, 'Call with one command-line argument'
assert isinstance(int(sys.argv[-1]), int)
# Use sympy to compute a rhs, given an analytical solution
x, y = symbols("x,y", real=True)
#ue = sin(4*x)*exp(-x**2)
ue = cos(4*y)*hermite(4, x)*exp(-x**2/2)
fe = ue.diff(x, 2)+ue.diff(y, 2)
# Size of discretization
N = int(sys.argv[-1])
SD = FunctionSpace(N, 'Hermite')
K0 = FunctionSpace(N, 'Fourier', dtype='d')
T = TensorProductSpace(comm, (SD, K0), axes=(0, 1))
u = TrialFunction(T)
v = TestFunction(T)
# Get f on quad points
fj = Array(T, buffer=fe)
# Compute right hand side of Poisson equation
f_hat = Function(T)
f_hat = inner(v, -fj, output_array=f_hat)
# Get left hand side of Poisson equation
matrices = inner(grad(v), grad(u))
# Solve and transform to real space
u_hat = Function(T) # Solution spectral space
sol = la.SolverGeneric1ND(matrices)
u_hat = sol(f_hat, u_hat)
uq = u_hat.backward()
# Compare with analytical solution
uj = Array(T, buffer=ue)
assert np.allclose(uj, uq, atol=1e-5)
print('Error ', np.linalg.norm(uj-uq))
if 'pytest' not in os.environ:
import matplotlib.pyplot as plt
plt.figure()
X = T.local_mesh(True)
plt.contourf(X[0], X[1], uq)
plt.colorbar()
plt.figure()
plt.contourf(X[0], X[1], uj)
plt.colorbar()
plt.figure()
plt.contourf(X[0], X[1], uq-uj)
plt.colorbar()
plt.title('Error')
plt.figure()
X = T.local_mesh()
for x in np.squeeze(X[0]):
plt.plot((x, x), (np.squeeze(X[1])[0], np.squeeze(X[1])[-1]), 'k')
for y in np.squeeze(X[1]):
plt.plot((np.squeeze(X[0])[0], np.squeeze(X[0])[-1]), (y, y), 'k')
#plt.show()
| [
"matplotlib.pyplot.title",
"numpy.allclose",
"sympy.cos",
"matplotlib.pyplot.figure",
"numpy.linalg.norm",
"matplotlib.pyplot.contourf",
"sympy.hermite",
"matplotlib.pyplot.colorbar",
"shenfun.inner",
"shenfun.grad",
"sympy.exp",
"shenfun.FunctionSpace",
"numpy.squeeze",
"shenfun.TestFunct... | [((676, 701), 'sympy.symbols', 'symbols', (['"""x,y"""'], {'real': '(True)'}), "('x,y', real=True)\n", (683, 701), False, 'from sympy import symbols, exp, hermite, cos\n'), ((856, 883), 'shenfun.FunctionSpace', 'FunctionSpace', (['N', '"""Hermite"""'], {}), "(N, 'Hermite')\n", (869, 883), False, 'from shenfun import inner, grad, TestFunction, TrialFunction, la, Array, Function, FunctionSpace, TensorProductSpace, comm\n'), ((889, 927), 'shenfun.FunctionSpace', 'FunctionSpace', (['N', '"""Fourier"""'], {'dtype': '"""d"""'}), "(N, 'Fourier', dtype='d')\n", (902, 927), False, 'from shenfun import inner, grad, TestFunction, TrialFunction, la, Array, Function, FunctionSpace, TensorProductSpace, comm\n'), ((932, 979), 'shenfun.TensorProductSpace', 'TensorProductSpace', (['comm', '(SD, K0)'], {'axes': '(0, 1)'}), '(comm, (SD, K0), axes=(0, 1))\n', (950, 979), False, 'from shenfun import inner, grad, TestFunction, TrialFunction, la, Array, Function, FunctionSpace, TensorProductSpace, comm\n'), ((984, 1000), 'shenfun.TrialFunction', 'TrialFunction', (['T'], {}), '(T)\n', (997, 1000), False, 'from shenfun import inner, grad, TestFunction, TrialFunction, la, Array, Function, FunctionSpace, TensorProductSpace, comm\n'), ((1005, 1020), 'shenfun.TestFunction', 'TestFunction', (['T'], {}), '(T)\n', (1017, 1020), False, 'from shenfun import inner, grad, TestFunction, TrialFunction, la, Array, Function, FunctionSpace, TensorProductSpace, comm\n'), ((1050, 1069), 'shenfun.Array', 'Array', (['T'], {'buffer': 'fe'}), '(T, buffer=fe)\n', (1055, 1069), False, 'from shenfun import inner, grad, TestFunction, TrialFunction, la, Array, Function, FunctionSpace, TensorProductSpace, comm\n'), ((1125, 1136), 'shenfun.Function', 'Function', (['T'], {}), '(T)\n', (1133, 1136), False, 'from shenfun import inner, grad, TestFunction, TrialFunction, la, Array, Function, FunctionSpace, TensorProductSpace, comm\n'), ((1145, 1178), 'shenfun.inner', 'inner', (['v', '(-fj)'], {'output_array': 'f_hat'}), '(v, -fj, output_array=f_hat)\n', (1150, 1178), False, 'from shenfun import inner, grad, TestFunction, TrialFunction, la, Array, Function, FunctionSpace, TensorProductSpace, comm\n'), ((1301, 1312), 'shenfun.Function', 'Function', (['T'], {}), '(T)\n', (1309, 1312), False, 'from shenfun import inner, grad, TestFunction, TrialFunction, la, Array, Function, FunctionSpace, TensorProductSpace, comm\n'), ((1355, 1384), 'shenfun.la.SolverGeneric1ND', 'la.SolverGeneric1ND', (['matrices'], {}), '(matrices)\n', (1374, 1384), False, 'from shenfun import inner, grad, TestFunction, TrialFunction, la, Array, Function, FunctionSpace, TensorProductSpace, comm\n'), ((1474, 1493), 'shenfun.Array', 'Array', (['T'], {'buffer': 'ue'}), '(T, buffer=ue)\n', (1479, 1493), False, 'from shenfun import inner, grad, TestFunction, TrialFunction, la, Array, Function, FunctionSpace, TensorProductSpace, comm\n'), ((1501, 1532), 'numpy.allclose', 'np.allclose', (['uj', 'uq'], {'atol': '(1e-05)'}), '(uj, uq, atol=1e-05)\n', (1512, 1532), True, 'import numpy as np\n'), ((756, 772), 'sympy.exp', 'exp', (['(-x ** 2 / 2)'], {}), '(-x ** 2 / 2)\n', (759, 772), False, 'from sympy import symbols, exp, hermite, cos\n'), ((1238, 1245), 'shenfun.grad', 'grad', (['v'], {}), '(v)\n', (1242, 1245), False, 'from shenfun import inner, grad, TestFunction, TrialFunction, la, Array, Function, FunctionSpace, TensorProductSpace, comm\n'), ((1247, 1254), 'shenfun.grad', 'grad', (['u'], {}), '(u)\n', (1251, 1254), False, 'from shenfun import inner, grad, TestFunction, TrialFunction, la, Array, Function, FunctionSpace, TensorProductSpace, comm\n'), ((1548, 1571), 'numpy.linalg.norm', 'np.linalg.norm', (['(uj - uq)'], {}), '(uj - uq)\n', (1562, 1571), True, 'import numpy as np\n'), ((1642, 1654), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (1652, 1654), True, 'import matplotlib.pyplot as plt\n'), ((1686, 1714), 'matplotlib.pyplot.contourf', 'plt.contourf', (['X[0]', 'X[1]', 'uq'], {}), '(X[0], X[1], uq)\n', (1698, 1714), True, 'import matplotlib.pyplot as plt\n'), ((1719, 1733), 'matplotlib.pyplot.colorbar', 'plt.colorbar', ([], {}), '()\n', (1731, 1733), True, 'import matplotlib.pyplot as plt\n'), ((1739, 1751), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (1749, 1751), True, 'import matplotlib.pyplot as plt\n'), ((1756, 1784), 'matplotlib.pyplot.contourf', 'plt.contourf', (['X[0]', 'X[1]', 'uj'], {}), '(X[0], X[1], uj)\n', (1768, 1784), True, 'import matplotlib.pyplot as plt\n'), ((1789, 1803), 'matplotlib.pyplot.colorbar', 'plt.colorbar', ([], {}), '()\n', (1801, 1803), True, 'import matplotlib.pyplot as plt\n'), ((1809, 1821), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (1819, 1821), True, 'import matplotlib.pyplot as plt\n'), ((1826, 1859), 'matplotlib.pyplot.contourf', 'plt.contourf', (['X[0]', 'X[1]', '(uq - uj)'], {}), '(X[0], X[1], uq - uj)\n', (1838, 1859), True, 'import matplotlib.pyplot as plt\n'), ((1862, 1876), 'matplotlib.pyplot.colorbar', 'plt.colorbar', ([], {}), '()\n', (1874, 1876), True, 'import matplotlib.pyplot as plt\n'), ((1881, 1899), 'matplotlib.pyplot.title', 'plt.title', (['"""Error"""'], {}), "('Error')\n", (1890, 1899), True, 'import matplotlib.pyplot as plt\n'), ((1905, 1917), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (1915, 1917), True, 'import matplotlib.pyplot as plt\n'), ((1954, 1970), 'numpy.squeeze', 'np.squeeze', (['X[0]'], {}), '(X[0])\n', (1964, 1970), True, 'import numpy as np\n'), ((2060, 2076), 'numpy.squeeze', 'np.squeeze', (['X[1]'], {}), '(X[1])\n', (2070, 2076), True, 'import numpy as np\n'), ((733, 743), 'sympy.cos', 'cos', (['(4 * y)'], {}), '(4 * y)\n', (736, 743), False, 'from sympy import symbols, exp, hermite, cos\n'), ((742, 755), 'sympy.hermite', 'hermite', (['(4)', 'x'], {}), '(4, x)\n', (749, 755), False, 'from sympy import symbols, exp, hermite, cos\n'), ((1998, 2014), 'numpy.squeeze', 'np.squeeze', (['X[1]'], {}), '(X[1])\n', (2008, 2014), True, 'import numpy as np\n'), ((2019, 2035), 'numpy.squeeze', 'np.squeeze', (['X[1]'], {}), '(X[1])\n', (2029, 2035), True, 'import numpy as np\n'), ((2096, 2112), 'numpy.squeeze', 'np.squeeze', (['X[0]'], {}), '(X[0])\n', (2106, 2112), True, 'import numpy as np\n'), ((2117, 2133), 'numpy.squeeze', 'np.squeeze', (['X[0]'], {}), '(X[0])\n', (2127, 2133), True, 'import numpy as np\n')] |
# Copyright 2017 The TensorFlow Authors. 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.
# ==============================================================================
"""Tests for image.understanding.object_detection.core.visualization_utils.
Testing with visualization in the following colab:
https://drive.google.com/a/google.com/file/d/0B5HnKS_hMsNARERpU3MtU3I5RFE/view?usp=sharing
"""
import numpy as np
import PIL.Image as Image
import tensorflow as tf
from object_detection.utils import visualization_utils
class VisualizationUtilsTest(tf.test.TestCase):
def create_colorful_test_image(self):
"""This function creates an image that can be used to test vis functions.
It makes an image composed of four colored rectangles.
Returns:
colorful test numpy array image.
"""
ch255 = np.full([100, 200, 1], 255, dtype=np.uint8)
ch128 = np.full([100, 200, 1], 128, dtype=np.uint8)
ch0 = np.full([100, 200, 1], 0, dtype=np.uint8)
imr = np.concatenate((ch255, ch128, ch128), axis=2)
img = np.concatenate((ch255, ch255, ch0), axis=2)
imb = np.concatenate((ch255, ch0, ch255), axis=2)
imw = np.concatenate((ch128, ch128, ch128), axis=2)
imu = np.concatenate((imr, img), axis=1)
imd = np.concatenate((imb, imw), axis=1)
image = np.concatenate((imu, imd), axis=0)
return image
def test_draw_bounding_box_on_image(self):
test_image = self.create_colorful_test_image()
test_image = Image.fromarray(test_image)
width_original, height_original = test_image.size
ymin = 0.25
ymax = 0.75
xmin = 0.4
xmax = 0.6
visualization_utils.draw_bounding_box_on_image(test_image, ymin, xmin,
ymax, xmax)
width_final, height_final = test_image.size
self.assertEqual(width_original, width_final)
self.assertEqual(height_original, height_final)
def test_draw_bounding_box_on_image_array(self):
test_image = self.create_colorful_test_image()
width_original = test_image.shape[0]
height_original = test_image.shape[1]
ymin = 0.25
ymax = 0.75
xmin = 0.4
xmax = 0.6
visualization_utils.draw_bounding_box_on_image_array(
test_image, ymin, xmin, ymax, xmax)
width_final = test_image.shape[0]
height_final = test_image.shape[1]
self.assertEqual(width_original, width_final)
self.assertEqual(height_original, height_final)
def test_draw_bounding_boxes_on_image(self):
test_image = self.create_colorful_test_image()
test_image = Image.fromarray(test_image)
width_original, height_original = test_image.size
boxes = np.array([[0.25, 0.75, 0.4, 0.6], [0.1, 0.1, 0.9, 0.9]])
visualization_utils.draw_bounding_boxes_on_image(test_image, boxes)
width_final, height_final = test_image.size
self.assertEqual(width_original, width_final)
self.assertEqual(height_original, height_final)
def test_draw_bounding_boxes_on_image_array(self):
test_image = self.create_colorful_test_image()
width_original = test_image.shape[0]
height_original = test_image.shape[1]
boxes = np.array([[0.25, 0.75, 0.4, 0.6], [0.1, 0.1, 0.9, 0.9]])
visualization_utils.draw_bounding_boxes_on_image_array(
test_image, boxes)
width_final = test_image.shape[0]
height_final = test_image.shape[1]
self.assertEqual(width_original, width_final)
self.assertEqual(height_original, height_final)
def test_draw_keypoints_on_image(self):
test_image = self.create_colorful_test_image()
test_image = Image.fromarray(test_image)
width_original, height_original = test_image.size
keypoints = [[0.25, 0.75], [0.4, 0.6], [0.1, 0.1], [0.9, 0.9]]
visualization_utils.draw_keypoints_on_image(test_image, keypoints)
width_final, height_final = test_image.size
self.assertEqual(width_original, width_final)
self.assertEqual(height_original, height_final)
def test_draw_keypoints_on_image_array(self):
test_image = self.create_colorful_test_image()
width_original = test_image.shape[0]
height_original = test_image.shape[1]
keypoints = [[0.25, 0.75], [0.4, 0.6], [0.1, 0.1], [0.9, 0.9]]
visualization_utils.draw_keypoints_on_image_array(
test_image, keypoints)
width_final = test_image.shape[0]
height_final = test_image.shape[1]
self.assertEqual(width_original, width_final)
self.assertEqual(height_original, height_final)
def test_draw_mask_on_image_array(self):
test_image = np.asarray(
[[[0, 0, 0], [0, 0, 0]], [[0, 0, 0], [0, 0, 0]]], dtype=np.uint8)
mask = np.asarray([[0.0, 1.0], [1.0, 1.0]], dtype=np.float32)
expected_result = np.asarray(
[[[0, 0, 0], [0, 0, 127]], [[0, 0, 127], [0, 0, 127]]],
dtype=np.uint8)
visualization_utils.draw_mask_on_image_array(
test_image, mask, color='Blue', alpha=.5)
self.assertAllEqual(test_image, expected_result)
if __name__ == '__main__':
tf.test.main()
| [
"tensorflow.test.main",
"numpy.full",
"object_detection.utils.visualization_utils.draw_bounding_box_on_image_array",
"object_detection.utils.visualization_utils.draw_bounding_boxes_on_image",
"numpy.asarray",
"object_detection.utils.visualization_utils.draw_bounding_boxes_on_image_array",
"numpy.array",... | [((5826, 5840), 'tensorflow.test.main', 'tf.test.main', ([], {}), '()\n', (5838, 5840), True, 'import tensorflow as tf\n'), ((1350, 1393), 'numpy.full', 'np.full', (['[100, 200, 1]', '(255)'], {'dtype': 'np.uint8'}), '([100, 200, 1], 255, dtype=np.uint8)\n', (1357, 1393), True, 'import numpy as np\n'), ((1410, 1453), 'numpy.full', 'np.full', (['[100, 200, 1]', '(128)'], {'dtype': 'np.uint8'}), '([100, 200, 1], 128, dtype=np.uint8)\n', (1417, 1453), True, 'import numpy as np\n'), ((1468, 1509), 'numpy.full', 'np.full', (['[100, 200, 1]', '(0)'], {'dtype': 'np.uint8'}), '([100, 200, 1], 0, dtype=np.uint8)\n', (1475, 1509), True, 'import numpy as np\n'), ((1524, 1569), 'numpy.concatenate', 'np.concatenate', (['(ch255, ch128, ch128)'], {'axis': '(2)'}), '((ch255, ch128, ch128), axis=2)\n', (1538, 1569), True, 'import numpy as np\n'), ((1584, 1627), 'numpy.concatenate', 'np.concatenate', (['(ch255, ch255, ch0)'], {'axis': '(2)'}), '((ch255, ch255, ch0), axis=2)\n', (1598, 1627), True, 'import numpy as np\n'), ((1642, 1685), 'numpy.concatenate', 'np.concatenate', (['(ch255, ch0, ch255)'], {'axis': '(2)'}), '((ch255, ch0, ch255), axis=2)\n', (1656, 1685), True, 'import numpy as np\n'), ((1700, 1745), 'numpy.concatenate', 'np.concatenate', (['(ch128, ch128, ch128)'], {'axis': '(2)'}), '((ch128, ch128, ch128), axis=2)\n', (1714, 1745), True, 'import numpy as np\n'), ((1760, 1794), 'numpy.concatenate', 'np.concatenate', (['(imr, img)'], {'axis': '(1)'}), '((imr, img), axis=1)\n', (1774, 1794), True, 'import numpy as np\n'), ((1809, 1843), 'numpy.concatenate', 'np.concatenate', (['(imb, imw)'], {'axis': '(1)'}), '((imb, imw), axis=1)\n', (1823, 1843), True, 'import numpy as np\n'), ((1860, 1894), 'numpy.concatenate', 'np.concatenate', (['(imu, imd)'], {'axis': '(0)'}), '((imu, imd), axis=0)\n', (1874, 1894), True, 'import numpy as np\n'), ((2040, 2067), 'PIL.Image.fromarray', 'Image.fromarray', (['test_image'], {}), '(test_image)\n', (2055, 2067), True, 'import PIL.Image as Image\n'), ((2213, 2299), 'object_detection.utils.visualization_utils.draw_bounding_box_on_image', 'visualization_utils.draw_bounding_box_on_image', (['test_image', 'ymin', 'xmin', 'ymax', 'xmax'], {}), '(test_image, ymin, xmin, ymax,\n xmax)\n', (2259, 2299), False, 'from object_detection.utils import visualization_utils\n'), ((2801, 2893), 'object_detection.utils.visualization_utils.draw_bounding_box_on_image_array', 'visualization_utils.draw_bounding_box_on_image_array', (['test_image', 'ymin', 'xmin', 'ymax', 'xmax'], {}), '(test_image, ymin, xmin,\n ymax, xmax)\n', (2853, 2893), False, 'from object_detection.utils import visualization_utils\n'), ((3225, 3252), 'PIL.Image.fromarray', 'Image.fromarray', (['test_image'], {}), '(test_image)\n', (3240, 3252), True, 'import PIL.Image as Image\n'), ((3327, 3383), 'numpy.array', 'np.array', (['[[0.25, 0.75, 0.4, 0.6], [0.1, 0.1, 0.9, 0.9]]'], {}), '([[0.25, 0.75, 0.4, 0.6], [0.1, 0.1, 0.9, 0.9]])\n', (3335, 3383), True, 'import numpy as np\n'), ((3393, 3460), 'object_detection.utils.visualization_utils.draw_bounding_boxes_on_image', 'visualization_utils.draw_bounding_boxes_on_image', (['test_image', 'boxes'], {}), '(test_image, boxes)\n', (3441, 3460), False, 'from object_detection.utils import visualization_utils\n'), ((3842, 3898), 'numpy.array', 'np.array', (['[[0.25, 0.75, 0.4, 0.6], [0.1, 0.1, 0.9, 0.9]]'], {}), '([[0.25, 0.75, 0.4, 0.6], [0.1, 0.1, 0.9, 0.9]])\n', (3850, 3898), True, 'import numpy as np\n'), ((3908, 3981), 'object_detection.utils.visualization_utils.draw_bounding_boxes_on_image_array', 'visualization_utils.draw_bounding_boxes_on_image_array', (['test_image', 'boxes'], {}), '(test_image, boxes)\n', (3962, 3981), False, 'from object_detection.utils import visualization_utils\n'), ((4312, 4339), 'PIL.Image.fromarray', 'Image.fromarray', (['test_image'], {}), '(test_image)\n', (4327, 4339), True, 'import PIL.Image as Image\n'), ((4478, 4544), 'object_detection.utils.visualization_utils.draw_keypoints_on_image', 'visualization_utils.draw_keypoints_on_image', (['test_image', 'keypoints'], {}), '(test_image, keypoints)\n', (4521, 4544), False, 'from object_detection.utils import visualization_utils\n'), ((4985, 5057), 'object_detection.utils.visualization_utils.draw_keypoints_on_image_array', 'visualization_utils.draw_keypoints_on_image_array', (['test_image', 'keypoints'], {}), '(test_image, keypoints)\n', (5034, 5057), False, 'from object_detection.utils import visualization_utils\n'), ((5334, 5410), 'numpy.asarray', 'np.asarray', (['[[[0, 0, 0], [0, 0, 0]], [[0, 0, 0], [0, 0, 0]]]'], {'dtype': 'np.uint8'}), '([[[0, 0, 0], [0, 0, 0]], [[0, 0, 0], [0, 0, 0]]], dtype=np.uint8)\n', (5344, 5410), True, 'import numpy as np\n'), ((5439, 5493), 'numpy.asarray', 'np.asarray', (['[[0.0, 1.0], [1.0, 1.0]]'], {'dtype': 'np.float32'}), '([[0.0, 1.0], [1.0, 1.0]], dtype=np.float32)\n', (5449, 5493), True, 'import numpy as np\n'), ((5520, 5607), 'numpy.asarray', 'np.asarray', (['[[[0, 0, 0], [0, 0, 127]], [[0, 0, 127], [0, 0, 127]]]'], {'dtype': 'np.uint8'}), '([[[0, 0, 0], [0, 0, 127]], [[0, 0, 127], [0, 0, 127]]], dtype=np\n .uint8)\n', (5530, 5607), True, 'import numpy as np\n'), ((5636, 5727), 'object_detection.utils.visualization_utils.draw_mask_on_image_array', 'visualization_utils.draw_mask_on_image_array', (['test_image', 'mask'], {'color': '"""Blue"""', 'alpha': '(0.5)'}), "(test_image, mask, color='Blue',\n alpha=0.5)\n", (5680, 5727), False, 'from object_detection.utils import visualization_utils\n')] |
# -*- coding: utf-8 -*-
# context managers
# import colorama # type: ignore
import numpy as np # type: ignore
import os
import signal
from datetime import datetime
class RandomSeed:
""" change random seed within context """
def __init__(self, seed: int):
self.seed = seed
self.state = np.random.get_state()
def __enter__(self):
np.random.seed(self.seed)
def __exit__(self, *args):
np.random.set_state(self.state)
class ChDir:
""" change directory within context """
def __init__(self, path: str):
self.old_dir = os.getcwd()
self.new_dir = path
def __enter__(self):
os.chdir(self.new_dir)
def __exit__(self, *args):
os.chdir(self.old_dir)
class Timer:
""" record time spent within context """
def __init__(self, prompt: str):
self.prompt = prompt + ' takes time: '
def __enter__(self):
self.start = datetime.now()
def __exit__(self, *args):
print(self.prompt + str(datetime.now() - self.start))
# print(colorama.Fore.BLUE + \
# self.prompt + str(datetime.now() - self.start) + \
# colorama.Style.RESET_ALL)
class TimeOut:
""" timeout within context """
def __init__(self, seconds: int, message='time out'):
self.seconds = seconds
self.message = message
def __enter__(self):
self.old_handle = signal.signal(signal.SIGALRM, self.handle)
signal.setitimer(signal.ITIMER_REAL, self.seconds)
def __exit__(self, *args):
signal.setitimer(signal.ITIMER_REAL, 0)
signal.signal(signal.SIGALRM, self.old_handle)
def handle(self, *args):
raise TimeoutError(self.message)
| [
"numpy.random.seed",
"numpy.random.get_state",
"os.getcwd",
"numpy.random.set_state",
"signal.setitimer",
"signal.signal",
"datetime.datetime.now",
"os.chdir"
] | [((407, 428), 'numpy.random.get_state', 'np.random.get_state', ([], {}), '()\n', (426, 428), True, 'import numpy as np\n'), ((463, 488), 'numpy.random.seed', 'np.random.seed', (['self.seed'], {}), '(self.seed)\n', (477, 488), True, 'import numpy as np\n'), ((529, 560), 'numpy.random.set_state', 'np.random.set_state', (['self.state'], {}), '(self.state)\n', (548, 560), True, 'import numpy as np\n'), ((678, 689), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (687, 689), False, 'import os\n'), ((752, 774), 'os.chdir', 'os.chdir', (['self.new_dir'], {}), '(self.new_dir)\n', (760, 774), False, 'import os\n'), ((815, 837), 'os.chdir', 'os.chdir', (['self.old_dir'], {}), '(self.old_dir)\n', (823, 837), False, 'import os\n'), ((1029, 1043), 'datetime.datetime.now', 'datetime.now', ([], {}), '()\n', (1041, 1043), False, 'from datetime import datetime\n'), ((1510, 1552), 'signal.signal', 'signal.signal', (['signal.SIGALRM', 'self.handle'], {}), '(signal.SIGALRM, self.handle)\n', (1523, 1552), False, 'import signal\n'), ((1561, 1611), 'signal.setitimer', 'signal.setitimer', (['signal.ITIMER_REAL', 'self.seconds'], {}), '(signal.ITIMER_REAL, self.seconds)\n', (1577, 1611), False, 'import signal\n'), ((1652, 1691), 'signal.setitimer', 'signal.setitimer', (['signal.ITIMER_REAL', '(0)'], {}), '(signal.ITIMER_REAL, 0)\n', (1668, 1691), False, 'import signal\n'), ((1700, 1746), 'signal.signal', 'signal.signal', (['signal.SIGALRM', 'self.old_handle'], {}), '(signal.SIGALRM, self.old_handle)\n', (1713, 1746), False, 'import signal\n'), ((1108, 1122), 'datetime.datetime.now', 'datetime.now', ([], {}), '()\n', (1120, 1122), False, 'from datetime import datetime\n')] |
"""Script to run the NAF2 agent on the inverted pendulum.
Includes also a visualisation of the environment and a video."""
import os
import pickle
import random
import sys
import gym
import matplotlib.pyplot as plt
import numpy as np
import tensorflow as tf
from inverted_pendulum import PendulumEnv
from naf2_new import NAF
# set random seed
random_seed = 111
np.random.seed(random_seed)
random.seed(random_seed)
def plot_results(env, file_name):
# plotting
print('Now plotting')
rewards = env.rewards
initial_rewards = env.init_rewards
# print('initial_rewards :', initial_rewards)
iterations = []
final_rews = []
starts = []
sum_rews = []
mean_rews = []
for i in range(len(rewards)):
if (len(rewards[i]) > 0):
final_rews.append(rewards[i][len(rewards[i]) - 1])
iterations.append(len(rewards[i]))
sum_rews.append(np.sum(rewards[i]))
mean_rews.append(np.mean(rewards[i]))
try:
starts.append(initial_rewards[i])
except:
pass
plot_suffix = "" # f', number of iterations: {env.TOTAL_COUNTER}, Linac4 time: {env.TOTAL_COUNTER / 600:.1f} h'
fig, axs = plt.subplots(2, 1)
ax = axs[0]
color = 'blue'
ax.plot(iterations, c=color)
ax.set_ylabel('steps', color=color)
ax.tick_params(axis='y', labelcolor=color)
ax1 = plt.twinx(ax)
color = 'k'
ax1.plot(np.cumsum(iterations), c=color)
ax1.set_ylabel('cumulative steps', color=color)
ax.set_title('Iterations' + plot_suffix)
# fig.suptitle(label, fontsize=12)
ax = axs[1]
color = 'red'
ax.plot(starts, c=color)
ax.set_ylabel('starts', color=color)
ax.axhline(-0.05, ls=':', color='r')
ax.tick_params(axis='y', labelcolor=color)
ax.set_title('Final reward per episode') # + plot_suffix)
ax.set_xlabel('# episode')
ax1 = plt.twinx(ax)
color = 'lime'
ax1.set_ylabel('finals', color=color)
ax1.axhline(-0.05, ls=':', color=color)
ax1.tick_params(axis='y', labelcolor=color)
ax1.plot(final_rews, color=color)
fig.tight_layout()
plt.savefig(file_name + '_episodes.pdf')
plt.show()
fig, ax = plt.subplots(1, 1)
color = 'blue'
ax.plot(sum_rews, color)
ax.set_ylabel('cum. reward', color=color)
ax.set_xlabel('# episode')
ax.tick_params(axis='y', labelcolor=color)
ax1 = plt.twinx(ax)
color = 'lime'
ax1.plot(mean_rews, c=color)
ax1.set_ylabel('mean reward', color=color) # we already handled the x-label with ax1
ax1.tick_params(axis='y', labelcolor=color)
plt.savefig(file_name + '_rewards.pdf')
plt.show()
def plot_convergence(agent, file_name):
losses, vs = agent.losses, agent.vs
# losses2, vs2 = agent.losses2, agent.vs2
fig, ax = plt.subplots()
# ax.set_title(label)
ax.set_xlabel('# steps')
color = 'tab:blue'
# ax.semilogy(losses2, color=color)
ax.tick_params(axis='y', labelcolor=color)
ax.set_ylabel('td_loss', color=color)
ax.semilogy(losses, color=color)
# ax.set_ylim(0, 1)
ax1 = plt.twinx(ax)
# ax1.set_ylim(-2, 1)
color = 'lime'
ax1.set_ylabel('V', color=color) # we already handled the x-label with ax1
ax1.tick_params(axis='y', labelcolor=color)
ax1.plot(vs, color=color)
# ax1.plot(vs2, color=color)
plt.savefig(file_name + '_convergence' + '.pdf')
plt.show()
class MonitoringEnv(gym.Wrapper):
'''
Gym Wrapper to store information for scaling to correct scpace and for post analysis.
'''
def __init__(self, env, **kwargs):
self.plot_label = False
if 'plot_progress' in kwargs:
self.plot_label = kwargs.get('plot_progress')
gym.Wrapper.__init__(self, env)
self.rewards = []
self.init_rewards = []
self.current_episode = -1
self.current_step = -1
self.obs_dim = self.env.observation_space.shape
self.obs_high = self.env.observation_space.high
self.obs_low = self.env.observation_space.high
self.act_dim = self.env.action_space.shape
self.act_high = self.env.action_space.high
self.act_low = self.env.action_space.low
# state space definition
self.observation_space = gym.spaces.Box(low=-1.0,
high=1.0,
shape=self.obs_dim,
dtype=np.float64)
# action space definition
self.action_space = gym.spaces.Box(low=-1.0,
high=1.0,
shape=self.act_dim,
dtype=np.float64)
def scale_state_env(self, ob):
scale = (self.env.observation_space.high - self.env.observation_space.low)
return (2 * ob - (self.env.observation_space.high + self.env.observation_space.low)) / scale
def scale_rew(self, rew):
rew = (rew/10)+1
return np.clip(rew, -1, 1)
def reset(self, **kwargs):
self.current_step = 0
self.current_episode += 1
self.rewards.append([])
return self.scale_state_env(self.env.reset(**kwargs))
def step(self, action):
self.current_step += 1
ob, reward, done, info = self.env.step(self.descale_action_env(action)[0])
self.rewards[self.current_episode].append(reward)
if self.current_step >= 200:
done = True
if self.plot_label:
self.plot_results(self.current_episode)
ob = self.scale_state_env(ob)
reward = self.scale_rew(reward)
# env.render()
# print(action, ob, reward)
return ob, reward, done, info
def descale_action_env(self, act):
scale = (self.env.action_space.high - self.env.action_space.low)
return_value = (scale * act + self.env.action_space.high + self.env.action_space.low) / 2
return return_value
def plot_results(self, label):
# plotting
rewards = self.rewards
iterations = []
final_rews = []
starts = []
sum_rews = []
mean_rews = []
for i in range(len(rewards)):
if (len(rewards[i]) > 0):
final_rews.append(rewards[i][len(rewards[i]) - 1])
iterations.append(len(rewards[i]))
sum_rews.append(np.sum(rewards[i]))
mean_rews.append(np.mean(rewards[i]))
fig, ax = plt.subplots(1, 1)
ax.set_title(label=label)
color = 'blue'
ax.plot(sum_rews, color)
ax.set_ylabel('cum. reward', color=color)
ax.set_xlabel('# episode')
ax.tick_params(axis='y', labelcolor=color)
plt.show()
if __name__ == '__main__':
try:
random_seed = int(sys.argv[2])
except:
random_seed = 25
try:
file_name = sys.argv[1] + '_' + str(random_seed)
except:
file_name = 'Data/NEW_tests' + str(random_seed) + '_'
# set random seed
tf.random.set_seed(random_seed)
np.random.seed(random_seed)
try:
root_dir = sys.argv[3]
except:
root_dir = "checkpoints/pendulum_video2/"
directory = root_dir + file_name + '/'
if not os.path.exists(directory):
os.makedirs(directory)
try:
index = int(sys.argv[4])
parameter_list = [
dict()
]
parameters = parameter_list[index]
print('Just a test...')
except:
parameters = dict()
is_continued = False # False if is_train else True
# We normalize in a MonitoringEnv state action and reward to [-1,1] for the agent and plot results
env = MonitoringEnv(env=PendulumEnv(), plot_progress=False)
# If you want a video:
env = gym.wrappers.Monitor(env, "recording2", force=True, video_callable=lambda episode_id: episode_id%10==0)
nafnet_kwargs = dict(hidden_sizes=[100, 100], activation=tf.nn.tanh
, kernel_initializer=tf.random_normal_initializer(0, 0.05, seed=random_seed))
action_size = env.action_space.shape[-1]
noise_info = dict(noise_function=lambda action, nr: action + np.random.randn(action_size) * 1 / (nr + 1))
# the target network is updated at the end of each episode
# the number of episodes is executed each step in the environment
training_info = dict(polyak=0.999, batch_size=100, steps_per_batch=10, epochs=1,
learning_rate=1e-3, discount=0.9999)
# init the agent
agent = NAF(env=env, directory=directory, noise_info=noise_info,
is_continued=is_continued, q_smoothing=0.001, clipped_double_q=True,
training_info=training_info, save_frequency=5000,
**nafnet_kwargs)
# run the agent training
agent.training(warm_up_steps=200, initial_episode_length=200, max_episodes=100, max_steps=500)
# run the agent verification
# agent.verification(max_episodes=10, max_steps=500)
# plot the results
files = []
for f in os.listdir(directory):
if 'plot_data' in f and 'pkl' in f:
files.append(f)
print(files)
if len(files) > 0:
file_name = directory + f'plot_data_{len(files)}'
else:
file_name = directory + 'plot_data_0'
plot_convergence(agent=agent, file_name=file_name)
plot_results(env, file_name=file_name)
out_put_writer = open(file_name + '.pkl', 'wb')
out_rewards = env.rewards
# out_inits = env.initial_conditions
out_losses, out_vs = agent.losses, agent.vs
pickle.dump(out_rewards, out_put_writer, -1)
# pickle.dump(out_inits, out_put_writer, -1)
pickle.dump(out_losses, out_put_writer, -1)
pickle.dump(out_vs, out_put_writer, -1)
out_put_writer.close()
| [
"tensorflow.random.set_seed",
"pickle.dump",
"numpy.random.seed",
"numpy.sum",
"naf2_new.NAF",
"gym.wrappers.Monitor",
"numpy.clip",
"numpy.mean",
"numpy.random.randn",
"os.path.exists",
"inverted_pendulum.PendulumEnv",
"numpy.cumsum",
"random.seed",
"matplotlib.pyplot.subplots",
"gym.Wr... | [((366, 393), 'numpy.random.seed', 'np.random.seed', (['random_seed'], {}), '(random_seed)\n', (380, 393), True, 'import numpy as np\n'), ((394, 418), 'random.seed', 'random.seed', (['random_seed'], {}), '(random_seed)\n', (405, 418), False, 'import random\n'), ((1225, 1243), 'matplotlib.pyplot.subplots', 'plt.subplots', (['(2)', '(1)'], {}), '(2, 1)\n', (1237, 1243), True, 'import matplotlib.pyplot as plt\n'), ((1410, 1423), 'matplotlib.pyplot.twinx', 'plt.twinx', (['ax'], {}), '(ax)\n', (1419, 1423), True, 'import matplotlib.pyplot as plt\n'), ((1919, 1932), 'matplotlib.pyplot.twinx', 'plt.twinx', (['ax'], {}), '(ax)\n', (1928, 1932), True, 'import matplotlib.pyplot as plt\n'), ((2152, 2192), 'matplotlib.pyplot.savefig', 'plt.savefig', (["(file_name + '_episodes.pdf')"], {}), "(file_name + '_episodes.pdf')\n", (2163, 2192), True, 'import matplotlib.pyplot as plt\n'), ((2197, 2207), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (2205, 2207), True, 'import matplotlib.pyplot as plt\n'), ((2223, 2241), 'matplotlib.pyplot.subplots', 'plt.subplots', (['(1)', '(1)'], {}), '(1, 1)\n', (2235, 2241), True, 'import matplotlib.pyplot as plt\n'), ((2424, 2437), 'matplotlib.pyplot.twinx', 'plt.twinx', (['ax'], {}), '(ax)\n', (2433, 2437), True, 'import matplotlib.pyplot as plt\n'), ((2632, 2671), 'matplotlib.pyplot.savefig', 'plt.savefig', (["(file_name + '_rewards.pdf')"], {}), "(file_name + '_rewards.pdf')\n", (2643, 2671), True, 'import matplotlib.pyplot as plt\n'), ((2676, 2686), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (2684, 2686), True, 'import matplotlib.pyplot as plt\n'), ((2829, 2843), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {}), '()\n', (2841, 2843), True, 'import matplotlib.pyplot as plt\n'), ((3125, 3138), 'matplotlib.pyplot.twinx', 'plt.twinx', (['ax'], {}), '(ax)\n', (3134, 3138), True, 'import matplotlib.pyplot as plt\n'), ((3379, 3427), 'matplotlib.pyplot.savefig', 'plt.savefig', (["(file_name + '_convergence' + '.pdf')"], {}), "(file_name + '_convergence' + '.pdf')\n", (3390, 3427), True, 'import matplotlib.pyplot as plt\n'), ((3432, 3442), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (3440, 3442), True, 'import matplotlib.pyplot as plt\n'), ((7120, 7151), 'tensorflow.random.set_seed', 'tf.random.set_seed', (['random_seed'], {}), '(random_seed)\n', (7138, 7151), True, 'import tensorflow as tf\n'), ((7156, 7183), 'numpy.random.seed', 'np.random.seed', (['random_seed'], {}), '(random_seed)\n', (7170, 7183), True, 'import numpy as np\n'), ((7877, 7988), 'gym.wrappers.Monitor', 'gym.wrappers.Monitor', (['env', '"""recording2"""'], {'force': '(True)', 'video_callable': '(lambda episode_id: episode_id % 10 == 0)'}), "(env, 'recording2', force=True, video_callable=lambda\n episode_id: episode_id % 10 == 0)\n", (7897, 7988), False, 'import gym\n'), ((8628, 8830), 'naf2_new.NAF', 'NAF', ([], {'env': 'env', 'directory': 'directory', 'noise_info': 'noise_info', 'is_continued': 'is_continued', 'q_smoothing': '(0.001)', 'clipped_double_q': '(True)', 'training_info': 'training_info', 'save_frequency': '(5000)'}), '(env=env, directory=directory, noise_info=noise_info, is_continued=\n is_continued, q_smoothing=0.001, clipped_double_q=True, training_info=\n training_info, save_frequency=5000, **nafnet_kwargs)\n', (8631, 8830), False, 'from naf2_new import NAF\n'), ((9140, 9161), 'os.listdir', 'os.listdir', (['directory'], {}), '(directory)\n', (9150, 9161), False, 'import os\n'), ((9665, 9709), 'pickle.dump', 'pickle.dump', (['out_rewards', 'out_put_writer', '(-1)'], {}), '(out_rewards, out_put_writer, -1)\n', (9676, 9709), False, 'import pickle\n'), ((9764, 9807), 'pickle.dump', 'pickle.dump', (['out_losses', 'out_put_writer', '(-1)'], {}), '(out_losses, out_put_writer, -1)\n', (9775, 9807), False, 'import pickle\n'), ((9812, 9851), 'pickle.dump', 'pickle.dump', (['out_vs', 'out_put_writer', '(-1)'], {}), '(out_vs, out_put_writer, -1)\n', (9823, 9851), False, 'import pickle\n'), ((1453, 1474), 'numpy.cumsum', 'np.cumsum', (['iterations'], {}), '(iterations)\n', (1462, 1474), True, 'import numpy as np\n'), ((3762, 3793), 'gym.Wrapper.__init__', 'gym.Wrapper.__init__', (['self', 'env'], {}), '(self, env)\n', (3782, 3793), False, 'import gym\n'), ((4302, 4374), 'gym.spaces.Box', 'gym.spaces.Box', ([], {'low': '(-1.0)', 'high': '(1.0)', 'shape': 'self.obs_dim', 'dtype': 'np.float64'}), '(low=-1.0, high=1.0, shape=self.obs_dim, dtype=np.float64)\n', (4316, 4374), False, 'import gym\n'), ((4582, 4654), 'gym.spaces.Box', 'gym.spaces.Box', ([], {'low': '(-1.0)', 'high': '(1.0)', 'shape': 'self.act_dim', 'dtype': 'np.float64'}), '(low=-1.0, high=1.0, shape=self.act_dim, dtype=np.float64)\n', (4596, 4654), False, 'import gym\n'), ((5075, 5094), 'numpy.clip', 'np.clip', (['rew', '(-1)', '(1)'], {}), '(rew, -1, 1)\n', (5082, 5094), True, 'import numpy as np\n'), ((6573, 6591), 'matplotlib.pyplot.subplots', 'plt.subplots', (['(1)', '(1)'], {}), '(1, 1)\n', (6585, 6591), True, 'import matplotlib.pyplot as plt\n'), ((6826, 6836), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (6834, 6836), True, 'import matplotlib.pyplot as plt\n'), ((7343, 7368), 'os.path.exists', 'os.path.exists', (['directory'], {}), '(directory)\n', (7357, 7368), False, 'import os\n'), ((7378, 7400), 'os.makedirs', 'os.makedirs', (['directory'], {}), '(directory)\n', (7389, 7400), False, 'import os\n'), ((7804, 7817), 'inverted_pendulum.PendulumEnv', 'PendulumEnv', ([], {}), '()\n', (7815, 7817), False, 'from inverted_pendulum import PendulumEnv\n'), ((8100, 8155), 'tensorflow.random_normal_initializer', 'tf.random_normal_initializer', (['(0)', '(0.05)'], {'seed': 'random_seed'}), '(0, 0.05, seed=random_seed)\n', (8128, 8155), True, 'import tensorflow as tf\n'), ((913, 931), 'numpy.sum', 'np.sum', (['rewards[i]'], {}), '(rewards[i])\n', (919, 931), True, 'import numpy as np\n'), ((962, 981), 'numpy.mean', 'np.mean', (['rewards[i]'], {}), '(rewards[i])\n', (969, 981), True, 'import numpy as np\n'), ((6480, 6498), 'numpy.sum', 'np.sum', (['rewards[i]'], {}), '(rewards[i])\n', (6486, 6498), True, 'import numpy as np\n'), ((6533, 6552), 'numpy.mean', 'np.mean', (['rewards[i]'], {}), '(rewards[i])\n', (6540, 6552), True, 'import numpy as np\n'), ((8268, 8296), 'numpy.random.randn', 'np.random.randn', (['action_size'], {}), '(action_size)\n', (8283, 8296), True, 'import numpy as np\n')] |
# stdlib
from time import time
# 3p
import numpy as np
import fbpca
def norm2(X):
return fbpca.pca(X, k=1, raw=True)[1][0]
def cond1(M, L, S, eps1):
return np.linalg.norm(M - L - S, ord='fro') <= eps1 * np.linalg.norm(M, ord='fro')
def shrinkage_operator(X, tau):
return np.sign(X) * np.max(np.abs(X) - tau, 0)
def sv_thresh_operator(X, tau, rank):
rank = min(rank, np.min(X.shape))
U, s, Vt = fbpca.pca(X, rank)
s -= tau
svp = (s > 0).sum()
return U[:, :svp] @ np.diag(s[:svp]) @ Vt[:svp], svp
def pcp(M, maxiter=10):
trans = False
if M.shape[0] < M.shape[1]:
M = M.T
trans = True
norm0 = np.linalg.norm(M, ord='fro')
# recommended parameters
eps1, eps2 = 1e-7, 1e-5
rho = 1.6
mu = 1.25 / norm2(M)
lamda = 1 / np.sqrt(M.shape[0])
sv = 10
# initialization
S, S_1, L = np.zeros_like(M), np.zeros_like(M), np.zeros_like(M)
Y = M / max(norm2(M), np.max(np.abs(M / lamda)))
# main loop
since = time()
for i in range(maxiter):
S_1 = S.copy()
S = shrinkage_operator(M - L + Y / mu, lamda / mu)
L, svp = sv_thresh_operator(M - S + Y / mu, 1 / mu, sv)
Y += mu * (M - L - S)
# check for convergence
cond2 = (mu * np.linalg.norm(S - S_1, ord='fro') / norm0) < eps2
if cond1(M, L, S, eps1) and cond2:
print(f'PCP converged! Took {round(time()-since, 2)} s')
break
# update mu and sv
sv = svp + (1 if svp < sv else round(0.05 * M.shape[1]))
mu = mu * rho if cond2 else mu
else:
print(f'Convergence Not reached! Took {round(time()-since, 2)} s')
return (L, S) if not trans else (L.T, S.T)
| [
"numpy.zeros_like",
"numpy.abs",
"fbpca.pca",
"time.time",
"numpy.min",
"numpy.linalg.norm",
"numpy.sign",
"numpy.diag",
"numpy.sqrt"
] | [((422, 440), 'fbpca.pca', 'fbpca.pca', (['X', 'rank'], {}), '(X, rank)\n', (431, 440), False, 'import fbpca\n'), ((660, 688), 'numpy.linalg.norm', 'np.linalg.norm', (['M'], {'ord': '"""fro"""'}), "(M, ord='fro')\n", (674, 688), True, 'import numpy as np\n'), ((1006, 1012), 'time.time', 'time', ([], {}), '()\n', (1010, 1012), False, 'from time import time\n'), ((168, 204), 'numpy.linalg.norm', 'np.linalg.norm', (['(M - L - S)'], {'ord': '"""fro"""'}), "(M - L - S, ord='fro')\n", (182, 204), True, 'import numpy as np\n'), ((289, 299), 'numpy.sign', 'np.sign', (['X'], {}), '(X)\n', (296, 299), True, 'import numpy as np\n'), ((390, 405), 'numpy.min', 'np.min', (['X.shape'], {}), '(X.shape)\n', (396, 405), True, 'import numpy as np\n'), ((802, 821), 'numpy.sqrt', 'np.sqrt', (['M.shape[0]'], {}), '(M.shape[0])\n', (809, 821), True, 'import numpy as np\n'), ((871, 887), 'numpy.zeros_like', 'np.zeros_like', (['M'], {}), '(M)\n', (884, 887), True, 'import numpy as np\n'), ((889, 905), 'numpy.zeros_like', 'np.zeros_like', (['M'], {}), '(M)\n', (902, 905), True, 'import numpy as np\n'), ((907, 923), 'numpy.zeros_like', 'np.zeros_like', (['M'], {}), '(M)\n', (920, 923), True, 'import numpy as np\n'), ((95, 122), 'fbpca.pca', 'fbpca.pca', (['X'], {'k': '(1)', 'raw': '(True)'}), '(X, k=1, raw=True)\n', (104, 122), False, 'import fbpca\n'), ((215, 243), 'numpy.linalg.norm', 'np.linalg.norm', (['M'], {'ord': '"""fro"""'}), "(M, ord='fro')\n", (229, 243), True, 'import numpy as np\n'), ((309, 318), 'numpy.abs', 'np.abs', (['X'], {}), '(X)\n', (315, 318), True, 'import numpy as np\n'), ((502, 518), 'numpy.diag', 'np.diag', (['s[:svp]'], {}), '(s[:svp])\n', (509, 518), True, 'import numpy as np\n'), ((957, 974), 'numpy.abs', 'np.abs', (['(M / lamda)'], {}), '(M / lamda)\n', (963, 974), True, 'import numpy as np\n'), ((1274, 1308), 'numpy.linalg.norm', 'np.linalg.norm', (['(S - S_1)'], {'ord': '"""fro"""'}), "(S - S_1, ord='fro')\n", (1288, 1308), True, 'import numpy as np\n'), ((1650, 1656), 'time.time', 'time', ([], {}), '()\n', (1654, 1656), False, 'from time import time\n'), ((1415, 1421), 'time.time', 'time', ([], {}), '()\n', (1419, 1421), False, 'from time import time\n')] |
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
"""
Assembly QC plots, including general statistics, base and mate coverages, and
scaffolding consistencies.
"""
from __future__ import print_function
import sys
import logging
import os.path as op
from jcvi.formats.fasta import Fasta
from jcvi.formats.bed import Bed, BedLine
from jcvi.formats.sizes import Sizes
from jcvi.assembly.base import calculate_A50
from jcvi.assembly.coverage import Coverage
from jcvi.graphics.base import plt, Rectangle, set_human_base_axis, savefig
from jcvi.utils.cbook import thousands
from jcvi.apps.base import OptionParser, ActionDispatcher, need_update
def main():
actions = (
('A50', 'compare A50 graphics for a set of FASTA files'),
('coverage', 'plot coverage from a set of BED files'),
('qc', 'performs QC graphics on given contig/scaffold'),
('scaffold', 'plot the alignment of the scaffold to other evidences'),
('covlen', 'plot coverage vs length'),
)
p = ActionDispatcher(actions)
p.dispatch(globals())
def covlen(args):
"""
%prog covlen covfile fastafile
Plot coverage vs length. `covfile` is two-column listing contig id and
depth of coverage.
"""
import numpy as np
import pandas as pd
import seaborn as sns
from jcvi.formats.base import DictFile
p = OptionParser(covlen.__doc__)
p.add_option("--maxsize", default=1000000, type="int", help="Max contig size")
p.add_option("--maxcov", default=100, type="int", help="Max contig size")
p.add_option("--color", default='m', help="Color of the data points")
p.add_option("--kind", default="scatter",
choices=("scatter", "reg", "resid", "kde", "hex"),
help="Kind of plot to draw")
opts, args, iopts = p.set_image_options(args, figsize="8x8")
if len(args) != 2:
sys.exit(not p.print_help())
covfile, fastafile = args
cov = DictFile(covfile, cast=float)
s = Sizes(fastafile)
data = []
maxsize, maxcov = opts.maxsize, opts.maxcov
for ctg, size in s.iter_sizes():
c = cov.get(ctg, 0)
if size > maxsize:
continue
if c > maxcov:
continue
data.append((size, c))
x, y = zip(*data)
x = np.array(x)
y = np.array(y)
logging.debug("X size {0}, Y size {1}".format(x.size, y.size))
df = pd.DataFrame()
xlab, ylab = "Length", "Coverage of depth (X)"
df[xlab] = x
df[ylab] = y
sns.jointplot(xlab, ylab, kind=opts.kind, data=df,
xlim=(0, maxsize), ylim=(0, maxcov),
stat_func=None, edgecolor="w", color=opts.color)
figname = covfile + ".pdf"
savefig(figname, dpi=iopts.dpi, iopts=iopts)
def coverage(args):
"""
%prog coverage fastafile ctg bedfile1 bedfile2 ..
Plot coverage from a set of BED files that contain the read mappings. The
paired read span will be converted to a new bedfile that contain the happy
mates. ctg is the chr/scf/ctg that you want to plot the histogram on.
If the bedfiles already contain the clone spans, turn on --spans.
"""
from jcvi.formats.bed import mates, bedpe
p = OptionParser(coverage.__doc__)
p.add_option("--ymax", default=None, type="int",
help="Limit ymax [default: %default]")
p.add_option("--spans", default=False, action="store_true",
help="BED files already contain clone spans [default: %default]")
opts, args, iopts = p.set_image_options(args, figsize="8x5")
if len(args) < 3:
sys.exit(not p.print_help())
fastafile, ctg = args[0:2]
bedfiles = args[2:]
sizes = Sizes(fastafile)
size = sizes.mapping[ctg]
plt.figure(1, (iopts.w, iopts.h))
ax = plt.gca()
bins = 100 # smooth the curve
lines = []
legends = []
not_covered = []
yy = .9
for bedfile, c in zip(bedfiles, "rgbcky"):
if not opts.spans:
pf = bedfile.rsplit(".", 1)[0]
matesfile = pf + ".mates"
if need_update(bedfile, matesfile):
matesfile, matesbedfile = mates([bedfile, "--lib"])
bedspanfile = pf + ".spans.bed"
if need_update(matesfile, bedspanfile):
bedpefile, bedspanfile = bedpe([bedfile, "--span",
"--mates={0}".format(matesfile)])
bedfile = bedspanfile
bedsum = Bed(bedfile).sum(seqid=ctg)
notcoveredbases = size - bedsum
legend = bedfile.split(".")[0]
msg = "{0}: {1} bp not covered".format(legend, thousands(notcoveredbases))
not_covered.append(msg)
print(msg, file=sys.stderr)
ax.text(.1, yy, msg, color=c, size=9, transform=ax.transAxes)
yy -= .08
cov = Coverage(bedfile, sizes.filename)
x, y = cov.get_plot_data(ctg, bins=bins)
line, = ax.plot(x, y, '-', color=c, lw=2, alpha=.5)
lines.append(line)
legends.append(legend)
leg = ax.legend(lines, legends, shadow=True, fancybox=True)
leg.get_frame().set_alpha(.5)
ylabel = "Average depth per {0}Kb".format(size / bins / 1000)
ax.set_xlim(0, size)
ax.set_ylim(0, opts.ymax)
ax.set_xlabel(ctg)
ax.set_ylabel(ylabel)
set_human_base_axis(ax)
figname ="{0}.{1}.pdf".format(fastafile, ctg)
savefig(figname, dpi=iopts.dpi, iopts=iopts)
def scaffolding(ax, scaffoldID, blastf, qsizes, ssizes, qbed, sbed,
highlights=None):
from jcvi.graphics.blastplot import blastplot
# qsizes, qbed are properties for the evidences
# ssizes, sbed are properties for the current scaffoldID
blastplot(ax, blastf, qsizes, ssizes, qbed, sbed, \
style="circle", insetLabels=True, stripNames=True,
highlights=highlights)
# FPC_scf.bed => FPC
fname = qbed.filename.split(".")[0].split("_")[0]
xtitle = fname
if xtitle == "FPC":
ax.set_xticklabels([""] * len(ax.get_xticklabels()))
ax.set_xlabel(xtitle, color="g")
for x in ax.get_xticklines():
x.set_visible(False)
def plot_one_scaffold(scaffoldID, ssizes, sbed, trios, imagename, iopts,
highlights=None):
ntrios = len(trios)
fig = plt.figure(1, (14, 8))
plt.cla()
plt.clf()
root = fig.add_axes([0, 0, 1, 1])
axes = [fig.add_subplot(1, ntrios, x) for x in range(1, ntrios + 1)]
scafsize = ssizes.get_size(scaffoldID)
for trio, ax in zip(trios, axes):
blastf, qsizes, qbed = trio
scaffolding(ax, scaffoldID, blastf, qsizes, ssizes, qbed, sbed,
highlights=highlights)
root.text(.5, .95, "{0} (size={1})".format(scaffoldID, thousands(scafsize)),
size=18, ha="center", color='b')
root.set_xlim(0, 1)
root.set_ylim(0, 1)
root.set_axis_off()
savefig(imagename, dpi=iopts.dpi, iopts=iopts)
def scaffold(args):
"""
%prog scaffold scaffold.fasta synteny.blast synteny.sizes synteny.bed
physicalmap.blast physicalmap.sizes physicalmap.bed
As evaluation of scaffolding, visualize external line of evidences:
* Plot synteny to an external genome
* Plot alignments to physical map
* Plot alignments to genetic map (TODO)
Each trio defines one panel to be plotted. blastfile defines the matchings
between the evidences vs scaffolds. Then the evidence sizes, and evidence
bed to plot dot plots.
This script will plot a dot in the dot plot in the corresponding location
the plots are one contig/scaffold per plot.
"""
from jcvi.utils.iter import grouper
p = OptionParser(scaffold.__doc__)
p.add_option("--cutoff", type="int", default=1000000,
help="Plot scaffolds with size larger than [default: %default]")
p.add_option("--highlights",
help="A set of regions in BED format to highlight [default: %default]")
opts, args, iopts = p.set_image_options(args, figsize="14x8", dpi=150)
if len(args) < 4 or len(args) % 3 != 1:
sys.exit(not p.print_help())
highlights = opts.highlights
scafsizes = Sizes(args[0])
trios = list(grouper(args[1:], 3))
trios = [(a, Sizes(b), Bed(c)) for a, b, c in trios]
if highlights:
hlbed = Bed(highlights)
for scaffoldID, scafsize in scafsizes.iter_sizes():
if scafsize < opts.cutoff:
continue
logging.debug("Loading {0} (size={1})".format(scaffoldID,
thousands(scafsize)))
tmpname = scaffoldID + ".sizes"
tmp = open(tmpname, "w")
tmp.write("{0}\t{1}".format(scaffoldID, scafsize))
tmp.close()
tmpsizes = Sizes(tmpname)
tmpsizes.close(clean=True)
if highlights:
subhighlights = list(hlbed.sub_bed(scaffoldID))
imagename = ".".join((scaffoldID, opts.format))
plot_one_scaffold(scaffoldID, tmpsizes, None, trios, imagename, iopts,
highlights=subhighlights)
def qc(args):
"""
%prog qc prefix
Expects data files including:
1. `prefix.bedpe` draws Bezier curve between paired reads
2. `prefix.sizes` draws length of the contig/scaffold
3. `prefix.gaps.bed` mark the position of the gaps in sequence
4. `prefix.bed.coverage` plots the base coverage
5. `prefix.pairs.bed.coverage` plots the clone coverage
See assembly.coverage.posmap() for the generation of these files.
"""
from jcvi.graphics.glyph import Bezier
p = OptionParser(qc.__doc__)
opts, args = p.parse_args(args)
if len(args) != 1:
sys.exit(p.print_help())
prefix, = args
scf = prefix
# All these files *must* be present in the current folder
bedpefile = prefix + ".bedpe"
fastafile = prefix + ".fasta"
sizesfile = prefix + ".sizes"
gapsbedfile = prefix + ".gaps.bed"
bedfile = prefix + ".bed"
bedpefile = prefix + ".bedpe"
pairsbedfile = prefix + ".pairs.bed"
sizes = Sizes(fastafile).mapping
size = sizes[scf]
fig = plt.figure(1, (8, 5))
root = fig.add_axes([0, 0, 1, 1])
# the scaffold
root.add_patch(Rectangle((.1, .15), .8, .03, fc='k'))
# basecoverage and matecoverage
ax = fig.add_axes([.1, .45, .8, .45])
bins = 200 # Smooth the curve
basecoverage = Coverage(bedfile, sizesfile)
matecoverage = Coverage(pairsbedfile, sizesfile)
x, y = basecoverage.get_plot_data(scf, bins=bins)
baseline, = ax.plot(x, y, 'g-')
x, y = matecoverage.get_plot_data(scf, bins=bins)
mateline, = ax.plot(x, y, 'r-')
legends = ("Base coverage", "Mate coverage")
leg = ax.legend((baseline, mateline), legends, shadow=True, fancybox=True)
leg.get_frame().set_alpha(.5)
ax.set_xlim(0, size)
# draw the read pairs
fp = open(bedpefile)
pairs = []
for row in fp:
scf, astart, aend, scf, bstart, bend, clonename = row.split()
astart, bstart = int(astart), int(bstart)
aend, bend = int(aend), int(bend)
start = min(astart, bstart) + 1
end = max(aend, bend)
pairs.append((start, end))
bpratio = .8 / size
cutoff = 1000 # inserts smaller than this are not plotted
# this convert from base => x-coordinate
pos = lambda x: (.1 + x * bpratio)
ypos = .15 + .03
for start, end in pairs:
dist = end - start
if dist < cutoff:
continue
dist = min(dist, 10000)
# 10Kb == .25 canvas height
height = .25 * dist / 10000
xstart = pos(start)
xend = pos(end)
p0 = (xstart, ypos)
p1 = (xstart, ypos + height)
p2 = (xend, ypos + height)
p3 = (xend, ypos)
Bezier(root, p0, p1, p2, p3)
# gaps on the scaffold
fp = open(gapsbedfile)
for row in fp:
b = BedLine(row)
start, end = b.start, b.end
xstart = pos(start)
xend = pos(end)
root.add_patch(Rectangle((xstart, .15), xend - xstart, .03, fc='w'))
root.text(.5, .1, scf, color='b', ha="center")
warn_msg = "Only the inserts > {0}bp are shown".format(cutoff)
root.text(.5, .1, scf, color='b', ha="center")
root.text(.5, .05, warn_msg, color='gray', ha="center")
# clean up and output
set_human_base_axis(ax)
root.set_xlim(0, 1)
root.set_ylim(0, 1)
root.set_axis_off()
figname = prefix + ".pdf"
savefig(figname, dpi=300)
def generate_plot(filename, rplot="A50.rplot", rpdf="A50.pdf"):
from jcvi.apps.r import RTemplate
rplot_template = """
library(ggplot2)
data <- read.table("$rplot", header=T, sep="\t")
g <- ggplot(data, aes(x=index, y=cumsize, group=fasta))
g + geom_line(aes(colour=fasta)) +
xlab("Contigs") + ylab("Cumulative size (Mb)") +
opts(title="A50 plot", legend.position="top")
ggsave(file="$rpdf")
"""
rtemplate = RTemplate(rplot_template, locals())
rtemplate.run()
def A50(args):
"""
%prog A50 contigs_A.fasta contigs_B.fasta ...
Plots A50 graphics, see blog post (http://blog.malde.org/index.php/a50/)
"""
p = OptionParser(A50.__doc__)
p.add_option("--overwrite", default=False, action="store_true",
help="overwrite .rplot file if exists [default: %default]")
p.add_option("--cutoff", default=0, type="int", dest="cutoff",
help="use contigs above certain size [default: %default]")
p.add_option("--stepsize", default=10, type="int", dest="stepsize",
help="stepsize for the distribution [default: %default]")
opts, args = p.parse_args(args)
if not args:
sys.exit(p.print_help())
import numpy as np
from jcvi.utils.table import loadtable
stepsize = opts.stepsize # use stepsize to speed up drawing
rplot = "A50.rplot"
if not op.exists(rplot) or opts.overwrite:
fw = open(rplot, "w")
header = "\t".join(("index", "cumsize", "fasta"))
statsheader = ("Fasta", "L50", "N50", "Min", "Max", "Average", "Sum",
"Counts")
statsrows = []
print(header, file=fw)
for fastafile in args:
f = Fasta(fastafile, index=False)
ctgsizes = [length for k, length in f.itersizes()]
ctgsizes = np.array(ctgsizes)
a50, l50, n50 = calculate_A50(ctgsizes, cutoff=opts.cutoff)
cmin, cmax, cmean = min(ctgsizes), max(ctgsizes), np.mean(ctgsizes)
csum, counts = np.sum(ctgsizes), len(ctgsizes)
cmean = int(round(cmean))
statsrows.append((fastafile, l50, n50, cmin, cmax, cmean, csum,
counts))
logging.debug("`{0}` ctgsizes: {1}".format(fastafile, ctgsizes))
tag = "{0} (L50={1})".format(\
op.basename(fastafile).rsplit(".", 1)[0], l50)
logging.debug(tag)
for i, s in zip(xrange(0, len(a50), stepsize), a50[::stepsize]):
print("\t".join((str(i), str(s / 1000000.), tag)), file=fw)
fw.close()
table = loadtable(statsheader, statsrows)
print(table, file=sys.stderr)
generate_plot(rplot)
if __name__ == '__main__':
main()
| [
"jcvi.formats.bed.mates",
"numpy.sum",
"jcvi.utils.iter.grouper",
"jcvi.graphics.base.set_human_base_axis",
"jcvi.assembly.coverage.Coverage",
"numpy.mean",
"jcvi.graphics.base.plt.gca",
"pandas.DataFrame",
"os.path.exists",
"jcvi.formats.base.DictFile",
"jcvi.graphics.base.plt.figure",
"jcvi.... | [((1010, 1035), 'jcvi.apps.base.ActionDispatcher', 'ActionDispatcher', (['actions'], {}), '(actions)\n', (1026, 1035), False, 'from jcvi.apps.base import OptionParser, ActionDispatcher, need_update\n'), ((1357, 1385), 'jcvi.apps.base.OptionParser', 'OptionParser', (['covlen.__doc__'], {}), '(covlen.__doc__)\n', (1369, 1385), False, 'from jcvi.apps.base import OptionParser, ActionDispatcher, need_update\n'), ((1948, 1977), 'jcvi.formats.base.DictFile', 'DictFile', (['covfile'], {'cast': 'float'}), '(covfile, cast=float)\n', (1956, 1977), False, 'from jcvi.formats.base import DictFile\n'), ((1986, 2002), 'jcvi.formats.sizes.Sizes', 'Sizes', (['fastafile'], {}), '(fastafile)\n', (1991, 2002), False, 'from jcvi.formats.sizes import Sizes\n'), ((2284, 2295), 'numpy.array', 'np.array', (['x'], {}), '(x)\n', (2292, 2295), True, 'import numpy as np\n'), ((2304, 2315), 'numpy.array', 'np.array', (['y'], {}), '(y)\n', (2312, 2315), True, 'import numpy as np\n'), ((2393, 2407), 'pandas.DataFrame', 'pd.DataFrame', ([], {}), '()\n', (2405, 2407), True, 'import pandas as pd\n'), ((2497, 2638), 'seaborn.jointplot', 'sns.jointplot', (['xlab', 'ylab'], {'kind': 'opts.kind', 'data': 'df', 'xlim': '(0, maxsize)', 'ylim': '(0, maxcov)', 'stat_func': 'None', 'edgecolor': '"""w"""', 'color': 'opts.color'}), "(xlab, ylab, kind=opts.kind, data=df, xlim=(0, maxsize), ylim=\n (0, maxcov), stat_func=None, edgecolor='w', color=opts.color)\n", (2510, 2638), True, 'import seaborn as sns\n'), ((2706, 2750), 'jcvi.graphics.base.savefig', 'savefig', (['figname'], {'dpi': 'iopts.dpi', 'iopts': 'iopts'}), '(figname, dpi=iopts.dpi, iopts=iopts)\n', (2713, 2750), False, 'from jcvi.graphics.base import plt, Rectangle, set_human_base_axis, savefig\n'), ((3201, 3231), 'jcvi.apps.base.OptionParser', 'OptionParser', (['coverage.__doc__'], {}), '(coverage.__doc__)\n', (3213, 3231), False, 'from jcvi.apps.base import OptionParser, ActionDispatcher, need_update\n'), ((3682, 3698), 'jcvi.formats.sizes.Sizes', 'Sizes', (['fastafile'], {}), '(fastafile)\n', (3687, 3698), False, 'from jcvi.formats.sizes import Sizes\n'), ((3734, 3767), 'jcvi.graphics.base.plt.figure', 'plt.figure', (['(1)', '(iopts.w, iopts.h)'], {}), '(1, (iopts.w, iopts.h))\n', (3744, 3767), False, 'from jcvi.graphics.base import plt, Rectangle, set_human_base_axis, savefig\n'), ((3777, 3786), 'jcvi.graphics.base.plt.gca', 'plt.gca', ([], {}), '()\n', (3784, 3786), False, 'from jcvi.graphics.base import plt, Rectangle, set_human_base_axis, savefig\n'), ((5266, 5289), 'jcvi.graphics.base.set_human_base_axis', 'set_human_base_axis', (['ax'], {}), '(ax)\n', (5285, 5289), False, 'from jcvi.graphics.base import plt, Rectangle, set_human_base_axis, savefig\n'), ((5345, 5389), 'jcvi.graphics.base.savefig', 'savefig', (['figname'], {'dpi': 'iopts.dpi', 'iopts': 'iopts'}), '(figname, dpi=iopts.dpi, iopts=iopts)\n', (5352, 5389), False, 'from jcvi.graphics.base import plt, Rectangle, set_human_base_axis, savefig\n'), ((5663, 5790), 'jcvi.graphics.blastplot.blastplot', 'blastplot', (['ax', 'blastf', 'qsizes', 'ssizes', 'qbed', 'sbed'], {'style': '"""circle"""', 'insetLabels': '(True)', 'stripNames': '(True)', 'highlights': 'highlights'}), "(ax, blastf, qsizes, ssizes, qbed, sbed, style='circle',\n insetLabels=True, stripNames=True, highlights=highlights)\n", (5672, 5790), False, 'from jcvi.graphics.blastplot import blastplot\n'), ((6250, 6272), 'jcvi.graphics.base.plt.figure', 'plt.figure', (['(1)', '(14, 8)'], {}), '(1, (14, 8))\n', (6260, 6272), False, 'from jcvi.graphics.base import plt, Rectangle, set_human_base_axis, savefig\n'), ((6277, 6286), 'jcvi.graphics.base.plt.cla', 'plt.cla', ([], {}), '()\n', (6284, 6286), False, 'from jcvi.graphics.base import plt, Rectangle, set_human_base_axis, savefig\n'), ((6291, 6300), 'jcvi.graphics.base.plt.clf', 'plt.clf', ([], {}), '()\n', (6298, 6300), False, 'from jcvi.graphics.base import plt, Rectangle, set_human_base_axis, savefig\n'), ((6851, 6897), 'jcvi.graphics.base.savefig', 'savefig', (['imagename'], {'dpi': 'iopts.dpi', 'iopts': 'iopts'}), '(imagename, dpi=iopts.dpi, iopts=iopts)\n', (6858, 6897), False, 'from jcvi.graphics.base import plt, Rectangle, set_human_base_axis, savefig\n'), ((7644, 7674), 'jcvi.apps.base.OptionParser', 'OptionParser', (['scaffold.__doc__'], {}), '(scaffold.__doc__)\n', (7656, 7674), False, 'from jcvi.apps.base import OptionParser, ActionDispatcher, need_update\n'), ((8134, 8148), 'jcvi.formats.sizes.Sizes', 'Sizes', (['args[0]'], {}), '(args[0])\n', (8139, 8148), False, 'from jcvi.formats.sizes import Sizes\n'), ((9514, 9538), 'jcvi.apps.base.OptionParser', 'OptionParser', (['qc.__doc__'], {}), '(qc.__doc__)\n', (9526, 9538), False, 'from jcvi.apps.base import OptionParser, ActionDispatcher, need_update\n'), ((10049, 10070), 'jcvi.graphics.base.plt.figure', 'plt.figure', (['(1)', '(8, 5)'], {}), '(1, (8, 5))\n', (10059, 10070), False, 'from jcvi.graphics.base import plt, Rectangle, set_human_base_axis, savefig\n'), ((10321, 10349), 'jcvi.assembly.coverage.Coverage', 'Coverage', (['bedfile', 'sizesfile'], {}), '(bedfile, sizesfile)\n', (10329, 10349), False, 'from jcvi.assembly.coverage import Coverage\n'), ((10369, 10402), 'jcvi.assembly.coverage.Coverage', 'Coverage', (['pairsbedfile', 'sizesfile'], {}), '(pairsbedfile, sizesfile)\n', (10377, 10402), False, 'from jcvi.assembly.coverage import Coverage\n'), ((12265, 12288), 'jcvi.graphics.base.set_human_base_axis', 'set_human_base_axis', (['ax'], {}), '(ax)\n', (12284, 12288), False, 'from jcvi.graphics.base import plt, Rectangle, set_human_base_axis, savefig\n'), ((12396, 12421), 'jcvi.graphics.base.savefig', 'savefig', (['figname'], {'dpi': '(300)'}), '(figname, dpi=300)\n', (12403, 12421), False, 'from jcvi.graphics.base import plt, Rectangle, set_human_base_axis, savefig\n'), ((13106, 13131), 'jcvi.apps.base.OptionParser', 'OptionParser', (['A50.__doc__'], {}), '(A50.__doc__)\n', (13118, 13131), False, 'from jcvi.apps.base import OptionParser, ActionDispatcher, need_update\n'), ((4791, 4824), 'jcvi.assembly.coverage.Coverage', 'Coverage', (['bedfile', 'sizes.filename'], {}), '(bedfile, sizes.filename)\n', (4799, 4824), False, 'from jcvi.assembly.coverage import Coverage\n'), ((8166, 8186), 'jcvi.utils.iter.grouper', 'grouper', (['args[1:]', '(3)'], {}), '(args[1:], 3)\n', (8173, 8186), False, 'from jcvi.utils.iter import grouper\n'), ((8280, 8295), 'jcvi.formats.bed.Bed', 'Bed', (['highlights'], {}), '(highlights)\n', (8283, 8295), False, 'from jcvi.formats.bed import Bed, BedLine\n'), ((8682, 8696), 'jcvi.formats.sizes.Sizes', 'Sizes', (['tmpname'], {}), '(tmpname)\n', (8687, 8696), False, 'from jcvi.formats.sizes import Sizes\n'), ((9991, 10007), 'jcvi.formats.sizes.Sizes', 'Sizes', (['fastafile'], {}), '(fastafile)\n', (9996, 10007), False, 'from jcvi.formats.sizes import Sizes\n'), ((10148, 10189), 'jcvi.graphics.base.Rectangle', 'Rectangle', (['(0.1, 0.15)', '(0.8)', '(0.03)'], {'fc': '"""k"""'}), "((0.1, 0.15), 0.8, 0.03, fc='k')\n", (10157, 10189), False, 'from jcvi.graphics.base import plt, Rectangle, set_human_base_axis, savefig\n'), ((11712, 11740), 'jcvi.graphics.glyph.Bezier', 'Bezier', (['root', 'p0', 'p1', 'p2', 'p3'], {}), '(root, p0, p1, p2, p3)\n', (11718, 11740), False, 'from jcvi.graphics.glyph import Bezier\n'), ((11827, 11839), 'jcvi.formats.bed.BedLine', 'BedLine', (['row'], {}), '(row)\n', (11834, 11839), False, 'from jcvi.formats.bed import Bed, BedLine\n'), ((15032, 15065), 'jcvi.utils.table.loadtable', 'loadtable', (['statsheader', 'statsrows'], {}), '(statsheader, statsrows)\n', (15041, 15065), False, 'from jcvi.utils.table import loadtable\n'), ((4058, 4089), 'jcvi.apps.base.need_update', 'need_update', (['bedfile', 'matesfile'], {}), '(bedfile, matesfile)\n', (4069, 4089), False, 'from jcvi.apps.base import OptionParser, ActionDispatcher, need_update\n'), ((4219, 4254), 'jcvi.apps.base.need_update', 'need_update', (['matesfile', 'bedspanfile'], {}), '(matesfile, bedspanfile)\n', (4230, 4254), False, 'from jcvi.apps.base import OptionParser, ActionDispatcher, need_update\n'), ((4592, 4618), 'jcvi.utils.cbook.thousands', 'thousands', (['notcoveredbases'], {}), '(notcoveredbases)\n', (4601, 4618), False, 'from jcvi.utils.cbook import thousands\n'), ((6707, 6726), 'jcvi.utils.cbook.thousands', 'thousands', (['scafsize'], {}), '(scafsize)\n', (6716, 6726), False, 'from jcvi.utils.cbook import thousands\n'), ((8205, 8213), 'jcvi.formats.sizes.Sizes', 'Sizes', (['b'], {}), '(b)\n', (8210, 8213), False, 'from jcvi.formats.sizes import Sizes\n'), ((8215, 8221), 'jcvi.formats.bed.Bed', 'Bed', (['c'], {}), '(c)\n', (8218, 8221), False, 'from jcvi.formats.bed import Bed, BedLine\n'), ((11951, 12005), 'jcvi.graphics.base.Rectangle', 'Rectangle', (['(xstart, 0.15)', '(xend - xstart)', '(0.03)'], {'fc': '"""w"""'}), "((xstart, 0.15), xend - xstart, 0.03, fc='w')\n", (11960, 12005), False, 'from jcvi.graphics.base import plt, Rectangle, set_human_base_axis, savefig\n'), ((13807, 13823), 'os.path.exists', 'op.exists', (['rplot'], {}), '(rplot)\n', (13816, 13823), True, 'import os.path as op\n'), ((14136, 14165), 'jcvi.formats.fasta.Fasta', 'Fasta', (['fastafile'], {'index': '(False)'}), '(fastafile, index=False)\n', (14141, 14165), False, 'from jcvi.formats.fasta import Fasta\n'), ((14252, 14270), 'numpy.array', 'np.array', (['ctgsizes'], {}), '(ctgsizes)\n', (14260, 14270), True, 'import numpy as np\n'), ((14300, 14343), 'jcvi.assembly.base.calculate_A50', 'calculate_A50', (['ctgsizes'], {'cutoff': 'opts.cutoff'}), '(ctgsizes, cutoff=opts.cutoff)\n', (14313, 14343), False, 'from jcvi.assembly.base import calculate_A50\n'), ((14823, 14841), 'logging.debug', 'logging.debug', (['tag'], {}), '(tag)\n', (14836, 14841), False, 'import logging\n'), ((4133, 4158), 'jcvi.formats.bed.mates', 'mates', (["[bedfile, '--lib']"], {}), "([bedfile, '--lib'])\n", (4138, 4158), False, 'from jcvi.formats.bed import mates, bedpe\n'), ((4429, 4441), 'jcvi.formats.bed.Bed', 'Bed', (['bedfile'], {}), '(bedfile)\n', (4432, 4441), False, 'from jcvi.formats.bed import Bed, BedLine\n'), ((8487, 8506), 'jcvi.utils.cbook.thousands', 'thousands', (['scafsize'], {}), '(scafsize)\n', (8496, 8506), False, 'from jcvi.utils.cbook import thousands\n'), ((14406, 14423), 'numpy.mean', 'np.mean', (['ctgsizes'], {}), '(ctgsizes)\n', (14413, 14423), True, 'import numpy as np\n'), ((14451, 14467), 'numpy.sum', 'np.sum', (['ctgsizes'], {}), '(ctgsizes)\n', (14457, 14467), True, 'import numpy as np\n'), ((14764, 14786), 'os.path.basename', 'op.basename', (['fastafile'], {}), '(fastafile)\n', (14775, 14786), True, 'import os.path as op\n')] |
import numpy as np
import matplotlib.pyplot as plt
from sealrtc.utils import genpsd, fs
plt.ion()
def design_from_ol(y, dt=1/fs, nseg=4):
"""
Designs a filter for a time-series of open loop values.
Arguments
---------
y : np.ndarray
The time-series.
dt : float
The time step in seconds.
nseg : int
The number of segments to use for the PSD.
Returns
-------
t : np.ndarray
The time axis for the impulse response.
x : np.ndarray
The impulse response.
"""
_, p = genpsd(y, dt=dt, nseg=nseg, remove_dc=False)
# fF = np.hstack((-np.flip(f[1:]), f))
xF = np.hstack((-np.flip(p[1:]), p))
x = np.fft.ifft(np.fft.fftshift(xF))
N = len(x)
t = np.arange(N) * dt
t = t[:N//2]
x = np.abs(x)[:N//2]
x = x / np.sum(x)
return t, x
def design_filt(dt=1, N=1024, fc=0.1, a=1e-6, tf=None, plot=True, oplot=False):
"""
Design a filter that takes white noise as input
and produces the f^-2/3 transitioning to f^-11/3 spectrum of atmospheric
tip/tilt. The way to do this is to put a "1/3" pole
near s=0 and a "3/2-pole" (11/3-2/3)/2 at the wind
clearing frequency, s=-fc
Inputs:
dt - time sample in seconds, float (defaults to 1.0 sec)
N - number of points in the resulting impulse response, integer
note: use a large number (default is 1024) to properly sample the spectrum over a
reasonable dynamic range.
fc - wind clearing frequency in Hz, float (defaults to 0.1 Hz)
a - the location of the "-1/3" pole, a small number on the real axis near the origin, float (defaults to 1e-6 Hz)
tf - the transfer function: a function that takes in 'f' and returns the corresponding point on the FT.
or just the PSD that we want to invert.
plot - if true, produce a plot of the impulse response and the power spectrum (default is True)
oplot - if true, prodece a plot, but overplot it on curves from a prior call to design_filt (default is False)
Output:
x - a time sequence representing the impulse response of the filter. The filter can be implemented
as a moving-average (MA) model using the values in x as the coefficients.
"""
i = 1j
if tf is not None and not callable(tf):
# the TF is just a power spectrum that's been passed in
xF = tf
m = len(tf) * 2
f = (np.arange(m)-m//2)/(m * dt)
else:
# we generate the TF from design parameters in the function args
f = (np.arange(N)-N//2)/(N * dt)
s = i*f
xF = ((s+a)**(-1/3)*(s+fc)**(-3/2))
# this is flipped, so that it tracks instead of controlling, and maybe 1/3 instead of 3/2 for an 1/f^2 powerlaw
if callable(tf):
xF = np.vectorize(tf)(f)
xF = np.fft.fftshift(xF)
f = np.fft.fftshift(f)
x = np.fft.ifft(xF)
t = np.arange(N)*dt
if plot:
if not oplot:
plt.figure(figsize=(6,7))
plt.subplot(211)
t = t[0:N//2]
x = x[0:N//2]
plt.plot(t, np.real(x))
plt.grid(True)
plt.ylabel('Impulse Response')
plt.xlabel('time, seconds')
plt.subplot(212)
f = f[1:N//2]
xF = xF[1:N//2]
plt.plot(f,np.abs(xF)**2)
plt.xscale('log')
plt.yscale('log')
plt.grid(True,which='both')
plt.ylabel('Power Spectrum')
plt.xlabel('frequency, Hz')
globals().update(locals())
return np.real(x) / sum(np.real(x))
def filt(a, dt=1, u=None, N=1024, plot=True, oplot=False):
'''filter the time series u by the filter a, defined
in terms of its impulse response
a is normalized to have unit integral
u defaults to white noise
Inputs:
a - the impulse response of the filter. This can be any length vector of floats
dt - the sample time, in seconds, float
u - the input sequence, a vector of floats.
Can be specified as None, in which case a white noise is generated in the routine. (defaults is None)
N - the length of the white noise sequence u if u is to be generated (otherwise N not used). integer (defaults to 1024)
plot - if True generate a plot of the resulting filter output time sequence and its power spectrum (default True)
oplot - if True, the plot will add a curve to a plot from a prior call of filt (default False)
Output:
y - the result of convolving u with the filter a
'''
a = a/np.sum(a)
n = len(a)
if u is None:
u = np.random.normal(size=(N,))
else:
N = len(u)
y = np.zeros(N)
t = dt*np.arange(N)
df = 1./(2 * N*dt) # I put in the factor of 2 here to match Ben's genpsd method
f = df*np.arange(1, N+1) # I changed arange(N) here to arange(1, N+1) here to match Ben's genpsd method
for k in range(N):
L = min(n,k+1)
y[k] = np.sum(u[range(k,k-L,-1)]*a[0:L])
if plot:
if not oplot:
plt.figure(figsize=(6,7))
lu = 'b-'
ly = 'r-'
else:
lu = 'b:'
ly = 'r:'
plt.subplot(211)
plt.plot(t,u,label='white noise')
plt.plot(t,y,label=r'tracked noise')
plt.grid(True)
plt.xlabel('time, seconds')
plt.legend()
plt.subplot(212)
uF = np.fft.fft(u)/N
yF = np.fft.fft(y)/N
uF = uF[1:N//2]
yF = yF[1:N//2]
uPSD = N*np.abs(uF)**2
yPSD = N*np.abs(yF)**2
f = f[1:N//2]
plt.plot(f,uPSD,lu,label='white noise')
plt.plot(f,yPSD,ly,label=r'filtered noise')
rPSD = (1/n)*(f*dt)**(-2/3)
plt.plot(f,rPSD,'k--')
cPSD = f**0
plt.plot(f,cPSD,'k--')
plt.xscale('log')
plt.yscale('log')
plt.grid(True,which='both')
plt.xlabel('frequency, Hz')
plt.legend()
globals().update(locals())
return y
| [
"matplotlib.pyplot.yscale",
"numpy.abs",
"numpy.sum",
"sealrtc.utils.genpsd",
"matplotlib.pyplot.figure",
"numpy.arange",
"numpy.random.normal",
"numpy.fft.fft",
"numpy.real",
"numpy.fft.ifft",
"numpy.vectorize",
"matplotlib.pyplot.legend",
"matplotlib.pyplot.ion",
"numpy.fft.fftshift",
... | [((90, 99), 'matplotlib.pyplot.ion', 'plt.ion', ([], {}), '()\n', (97, 99), True, 'import matplotlib.pyplot as plt\n'), ((540, 584), 'sealrtc.utils.genpsd', 'genpsd', (['y'], {'dt': 'dt', 'nseg': 'nseg', 'remove_dc': '(False)'}), '(y, dt=dt, nseg=nseg, remove_dc=False)\n', (546, 584), False, 'from sealrtc.utils import genpsd, fs\n'), ((2831, 2850), 'numpy.fft.fftshift', 'np.fft.fftshift', (['xF'], {}), '(xF)\n', (2846, 2850), True, 'import numpy as np\n'), ((2859, 2877), 'numpy.fft.fftshift', 'np.fft.fftshift', (['f'], {}), '(f)\n', (2874, 2877), True, 'import numpy as np\n'), ((2886, 2901), 'numpy.fft.ifft', 'np.fft.ifft', (['xF'], {}), '(xF)\n', (2897, 2901), True, 'import numpy as np\n'), ((4639, 4650), 'numpy.zeros', 'np.zeros', (['N'], {}), '(N)\n', (4647, 4650), True, 'import numpy as np\n'), ((689, 708), 'numpy.fft.fftshift', 'np.fft.fftshift', (['xF'], {}), '(xF)\n', (704, 708), True, 'import numpy as np\n'), ((733, 745), 'numpy.arange', 'np.arange', (['N'], {}), '(N)\n', (742, 745), True, 'import numpy as np\n'), ((776, 785), 'numpy.abs', 'np.abs', (['x'], {}), '(x)\n', (782, 785), True, 'import numpy as np\n'), ((805, 814), 'numpy.sum', 'np.sum', (['x'], {}), '(x)\n', (811, 814), True, 'import numpy as np\n'), ((2910, 2922), 'numpy.arange', 'np.arange', (['N'], {}), '(N)\n', (2919, 2922), True, 'import numpy as np\n'), ((3007, 3023), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(211)'], {}), '(211)\n', (3018, 3023), True, 'import matplotlib.pyplot as plt\n'), ((3108, 3122), 'matplotlib.pyplot.grid', 'plt.grid', (['(True)'], {}), '(True)\n', (3116, 3122), True, 'import matplotlib.pyplot as plt\n'), ((3131, 3161), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Impulse Response"""'], {}), "('Impulse Response')\n", (3141, 3161), True, 'import matplotlib.pyplot as plt\n'), ((3170, 3197), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""time, seconds"""'], {}), "('time, seconds')\n", (3180, 3197), True, 'import matplotlib.pyplot as plt\n'), ((3206, 3222), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(212)'], {}), '(212)\n', (3217, 3222), True, 'import matplotlib.pyplot as plt\n'), ((3311, 3328), 'matplotlib.pyplot.xscale', 'plt.xscale', (['"""log"""'], {}), "('log')\n", (3321, 3328), True, 'import matplotlib.pyplot as plt\n'), ((3337, 3354), 'matplotlib.pyplot.yscale', 'plt.yscale', (['"""log"""'], {}), "('log')\n", (3347, 3354), True, 'import matplotlib.pyplot as plt\n'), ((3363, 3391), 'matplotlib.pyplot.grid', 'plt.grid', (['(True)'], {'which': '"""both"""'}), "(True, which='both')\n", (3371, 3391), True, 'import matplotlib.pyplot as plt\n'), ((3399, 3427), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Power Spectrum"""'], {}), "('Power Spectrum')\n", (3409, 3427), True, 'import matplotlib.pyplot as plt\n'), ((3436, 3463), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""frequency, Hz"""'], {}), "('frequency, Hz')\n", (3446, 3463), True, 'import matplotlib.pyplot as plt\n'), ((3506, 3516), 'numpy.real', 'np.real', (['x'], {}), '(x)\n', (3513, 3516), True, 'import numpy as np\n'), ((4519, 4528), 'numpy.sum', 'np.sum', (['a'], {}), '(a)\n', (4525, 4528), True, 'import numpy as np\n'), ((4574, 4601), 'numpy.random.normal', 'np.random.normal', ([], {'size': '(N,)'}), '(size=(N,))\n', (4590, 4601), True, 'import numpy as np\n'), ((4662, 4674), 'numpy.arange', 'np.arange', (['N'], {}), '(N)\n', (4671, 4674), True, 'import numpy as np\n'), ((4770, 4789), 'numpy.arange', 'np.arange', (['(1)', '(N + 1)'], {}), '(1, N + 1)\n', (4779, 4789), True, 'import numpy as np\n'), ((5145, 5161), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(211)'], {}), '(211)\n', (5156, 5161), True, 'import matplotlib.pyplot as plt\n'), ((5170, 5205), 'matplotlib.pyplot.plot', 'plt.plot', (['t', 'u'], {'label': '"""white noise"""'}), "(t, u, label='white noise')\n", (5178, 5205), True, 'import matplotlib.pyplot as plt\n'), ((5212, 5249), 'matplotlib.pyplot.plot', 'plt.plot', (['t', 'y'], {'label': '"""tracked noise"""'}), "(t, y, label='tracked noise')\n", (5220, 5249), True, 'import matplotlib.pyplot as plt\n'), ((5257, 5271), 'matplotlib.pyplot.grid', 'plt.grid', (['(True)'], {}), '(True)\n', (5265, 5271), True, 'import matplotlib.pyplot as plt\n'), ((5280, 5307), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""time, seconds"""'], {}), "('time, seconds')\n", (5290, 5307), True, 'import matplotlib.pyplot as plt\n'), ((5316, 5328), 'matplotlib.pyplot.legend', 'plt.legend', ([], {}), '()\n', (5326, 5328), True, 'import matplotlib.pyplot as plt\n'), ((5337, 5353), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(212)'], {}), '(212)\n', (5348, 5353), True, 'import matplotlib.pyplot as plt\n'), ((5552, 5594), 'matplotlib.pyplot.plot', 'plt.plot', (['f', 'uPSD', 'lu'], {'label': '"""white noise"""'}), "(f, uPSD, lu, label='white noise')\n", (5560, 5594), True, 'import matplotlib.pyplot as plt\n'), ((5600, 5645), 'matplotlib.pyplot.plot', 'plt.plot', (['f', 'yPSD', 'ly'], {'label': '"""filtered noise"""'}), "(f, yPSD, ly, label='filtered noise')\n", (5608, 5645), True, 'import matplotlib.pyplot as plt\n'), ((5688, 5712), 'matplotlib.pyplot.plot', 'plt.plot', (['f', 'rPSD', '"""k--"""'], {}), "(f, rPSD, 'k--')\n", (5696, 5712), True, 'import matplotlib.pyplot as plt\n'), ((5739, 5763), 'matplotlib.pyplot.plot', 'plt.plot', (['f', 'cPSD', '"""k--"""'], {}), "(f, cPSD, 'k--')\n", (5747, 5763), True, 'import matplotlib.pyplot as plt\n'), ((5770, 5787), 'matplotlib.pyplot.xscale', 'plt.xscale', (['"""log"""'], {}), "('log')\n", (5780, 5787), True, 'import matplotlib.pyplot as plt\n'), ((5796, 5813), 'matplotlib.pyplot.yscale', 'plt.yscale', (['"""log"""'], {}), "('log')\n", (5806, 5813), True, 'import matplotlib.pyplot as plt\n'), ((5822, 5850), 'matplotlib.pyplot.grid', 'plt.grid', (['(True)'], {'which': '"""both"""'}), "(True, which='both')\n", (5830, 5850), True, 'import matplotlib.pyplot as plt\n'), ((5858, 5885), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""frequency, Hz"""'], {}), "('frequency, Hz')\n", (5868, 5885), True, 'import matplotlib.pyplot as plt\n'), ((5894, 5906), 'matplotlib.pyplot.legend', 'plt.legend', ([], {}), '()\n', (5904, 5906), True, 'import matplotlib.pyplot as plt\n'), ((2801, 2817), 'numpy.vectorize', 'np.vectorize', (['tf'], {}), '(tf)\n', (2813, 2817), True, 'import numpy as np\n'), ((2973, 2999), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(6, 7)'}), '(figsize=(6, 7))\n', (2983, 2999), True, 'import matplotlib.pyplot as plt\n'), ((3088, 3098), 'numpy.real', 'np.real', (['x'], {}), '(x)\n', (3095, 3098), True, 'import numpy as np\n'), ((3523, 3533), 'numpy.real', 'np.real', (['x'], {}), '(x)\n', (3530, 3533), True, 'import numpy as np\n'), ((5009, 5035), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(6, 7)'}), '(figsize=(6, 7))\n', (5019, 5035), True, 'import matplotlib.pyplot as plt\n'), ((5367, 5380), 'numpy.fft.fft', 'np.fft.fft', (['u'], {}), '(u)\n', (5377, 5380), True, 'import numpy as np\n'), ((5396, 5409), 'numpy.fft.fft', 'np.fft.fft', (['y'], {}), '(y)\n', (5406, 5409), True, 'import numpy as np\n'), ((649, 663), 'numpy.flip', 'np.flip', (['p[1:]'], {}), '(p[1:])\n', (656, 663), True, 'import numpy as np\n'), ((2439, 2451), 'numpy.arange', 'np.arange', (['m'], {}), '(m)\n', (2448, 2451), True, 'import numpy as np\n'), ((2563, 2575), 'numpy.arange', 'np.arange', (['N'], {}), '(N)\n', (2572, 2575), True, 'import numpy as np\n'), ((3288, 3298), 'numpy.abs', 'np.abs', (['xF'], {}), '(xF)\n', (3294, 3298), True, 'import numpy as np\n'), ((5477, 5487), 'numpy.abs', 'np.abs', (['uF'], {}), '(uF)\n', (5483, 5487), True, 'import numpy as np\n'), ((5508, 5518), 'numpy.abs', 'np.abs', (['yF'], {}), '(yF)\n', (5514, 5518), True, 'import numpy as np\n')] |
# Copyright 2021 Dakewe Biotech Corporation. 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.
# ==============================================================================
"""Realize the function of dataset preparation."""
import io
import os
import lmdb
import numpy as np
from PIL import Image
from torch import Tensor
from torch.utils.data import Dataset
from torchvision import transforms
from torchvision.transforms.functional import InterpolationMode as IMode
import imgproc
__all__ = ["ImageDataset", "LMDBDataset"]
class ImageDataset(Dataset):
"""Customize the data set loading function and prepare low/high resolution image data in advance.
Args:
dataroot (str): Training data set address
image_size (int): High resolution image size
upscale_factor (int): Image magnification
mode (str): Data set loading method, the training data set is for data enhancement,
and the verification data set is not for data enhancement
"""
def __init__(self, dataroot: str, image_size: int, upscale_factor: int, mode: str) -> None:
super(ImageDataset, self).__init__()
self.file_names = [os.path.join(dataroot, x) for x in os.listdir(dataroot)]
if mode == "train":
self.hr_transforms = transforms.RandomCrop(image_size)
else:
self.hr_transforms = transforms.CenterCrop(image_size)
self.lr_transforms = transforms.Compose([
transforms.Resize(image_size // upscale_factor, interpolation=IMode.BICUBIC, antialias=True),
transforms.Resize(image_size, interpolation=IMode.BICUBIC, antialias=True),
])
def __getitem__(self, batch_index: int) -> [Tensor, Tensor]:
# Read a batch of image data
image = Image.open(self.file_names[batch_index])
# Transform image
hr_image = self.hr_transforms(image)
lr_image = self.lr_transforms(hr_image)
# Only extract the image data of the Y channel
lr_image = np.array(lr_image).astype(np.float32)
hr_image = np.array(hr_image).astype(np.float32)
lr_ycbcr_image = imgproc.convert_rgb_to_ycbcr(lr_image)
hr_ycbcr_image = imgproc.convert_rgb_to_ycbcr(hr_image)
# Convert image data into Tensor stream format (PyTorch).
# Note: The range of input and output is between [0, 1]
lr_y_tensor = imgproc.image2tensor(lr_ycbcr_image, range_norm=False, half=False)
hr_y_tensor = imgproc.image2tensor(hr_ycbcr_image, range_norm=False, half=False)
return lr_y_tensor, hr_y_tensor
def __len__(self) -> int:
return len(self.file_names)
class LMDBDataset(Dataset):
"""Load the data set as a data set in the form of LMDB.
Attributes:
lr_datasets (list): Low-resolution image data in the dataset
hr_datasets (list): High-resolution image data in the dataset
"""
def __init__(self, lr_lmdb_path, hr_lmdb_path) -> None:
super(LMDBDataset, self).__init__()
# Create low/high resolution image array
self.lr_datasets = []
self.hr_datasets = []
# Initialize the LMDB database file address
self.lr_lmdb_path = lr_lmdb_path
self.hr_lmdb_path = hr_lmdb_path
# Write image data in LMDB database to memory
self.read_lmdb_dataset()
def __getitem__(self, batch_index: int) -> [Tensor, Tensor]:
# Read a batch of image data
lr_image = self.lr_datasets[batch_index]
hr_image = self.hr_datasets[batch_index]
# Only extract the image data of the Y channel
lr_image = np.array(lr_image).astype(np.float32)
hr_image = np.array(hr_image).astype(np.float32)
lr_ycbcr_image = imgproc.convert_rgb_to_ycbcr(lr_image)
hr_ycbcr_image = imgproc.convert_rgb_to_ycbcr(hr_image)
# Convert image data into Tensor stream format (PyTorch).
# Note: The range of input and output is between [0, 1]
lr_y_tensor = imgproc.image2tensor(lr_ycbcr_image, range_norm=False, half=False)
hr_y_tensor = imgproc.image2tensor(hr_ycbcr_image, range_norm=False, half=False)
return lr_y_tensor, hr_y_tensor
def __len__(self) -> int:
return len(self.lr_datasets)
def read_lmdb_dataset(self) -> [list, list]:
# Open two LMDB database writing environments to read low/high image data
lr_lmdb_env = lmdb.open(self.lr_lmdb_path)
hr_lmdb_env = lmdb.open(self.hr_lmdb_path)
# Write the image data in the low-resolution LMDB data set to the memory
for _, image_bytes in lr_lmdb_env.begin().cursor():
image = Image.open(io.BytesIO(image_bytes))
self.lr_datasets.append(image)
# Write the image data in the high-resolution LMDB data set to the memory
for _, image_bytes in hr_lmdb_env.begin().cursor():
image = Image.open(io.BytesIO(image_bytes))
self.hr_datasets.append(image)
| [
"io.BytesIO",
"imgproc.image2tensor",
"imgproc.convert_rgb_to_ycbcr",
"PIL.Image.open",
"numpy.array",
"lmdb.open",
"torchvision.transforms.CenterCrop",
"os.path.join",
"os.listdir",
"torchvision.transforms.RandomCrop",
"torchvision.transforms.Resize"
] | [((2342, 2382), 'PIL.Image.open', 'Image.open', (['self.file_names[batch_index]'], {}), '(self.file_names[batch_index])\n', (2352, 2382), False, 'from PIL import Image\n'), ((2698, 2736), 'imgproc.convert_rgb_to_ycbcr', 'imgproc.convert_rgb_to_ycbcr', (['lr_image'], {}), '(lr_image)\n', (2726, 2736), False, 'import imgproc\n'), ((2762, 2800), 'imgproc.convert_rgb_to_ycbcr', 'imgproc.convert_rgb_to_ycbcr', (['hr_image'], {}), '(hr_image)\n', (2790, 2800), False, 'import imgproc\n'), ((2954, 3020), 'imgproc.image2tensor', 'imgproc.image2tensor', (['lr_ycbcr_image'], {'range_norm': '(False)', 'half': '(False)'}), '(lr_ycbcr_image, range_norm=False, half=False)\n', (2974, 3020), False, 'import imgproc\n'), ((3043, 3109), 'imgproc.image2tensor', 'imgproc.image2tensor', (['hr_ycbcr_image'], {'range_norm': '(False)', 'half': '(False)'}), '(hr_ycbcr_image, range_norm=False, half=False)\n', (3063, 3109), False, 'import imgproc\n'), ((4306, 4344), 'imgproc.convert_rgb_to_ycbcr', 'imgproc.convert_rgb_to_ycbcr', (['lr_image'], {}), '(lr_image)\n', (4334, 4344), False, 'import imgproc\n'), ((4370, 4408), 'imgproc.convert_rgb_to_ycbcr', 'imgproc.convert_rgb_to_ycbcr', (['hr_image'], {}), '(hr_image)\n', (4398, 4408), False, 'import imgproc\n'), ((4562, 4628), 'imgproc.image2tensor', 'imgproc.image2tensor', (['lr_ycbcr_image'], {'range_norm': '(False)', 'half': '(False)'}), '(lr_ycbcr_image, range_norm=False, half=False)\n', (4582, 4628), False, 'import imgproc\n'), ((4651, 4717), 'imgproc.image2tensor', 'imgproc.image2tensor', (['hr_ycbcr_image'], {'range_norm': '(False)', 'half': '(False)'}), '(hr_ycbcr_image, range_norm=False, half=False)\n', (4671, 4717), False, 'import imgproc\n'), ((4981, 5009), 'lmdb.open', 'lmdb.open', (['self.lr_lmdb_path'], {}), '(self.lr_lmdb_path)\n', (4990, 5009), False, 'import lmdb\n'), ((5032, 5060), 'lmdb.open', 'lmdb.open', (['self.hr_lmdb_path'], {}), '(self.hr_lmdb_path)\n', (5041, 5060), False, 'import lmdb\n'), ((1733, 1758), 'os.path.join', 'os.path.join', (['dataroot', 'x'], {}), '(dataroot, x)\n', (1745, 1758), False, 'import os\n'), ((1852, 1885), 'torchvision.transforms.RandomCrop', 'transforms.RandomCrop', (['image_size'], {}), '(image_size)\n', (1873, 1885), False, 'from torchvision import transforms\n'), ((1933, 1966), 'torchvision.transforms.CenterCrop', 'transforms.CenterCrop', (['image_size'], {}), '(image_size)\n', (1954, 1966), False, 'from torchvision import transforms\n'), ((1768, 1788), 'os.listdir', 'os.listdir', (['dataroot'], {}), '(dataroot)\n', (1778, 1788), False, 'import os\n'), ((2030, 2126), 'torchvision.transforms.Resize', 'transforms.Resize', (['(image_size // upscale_factor)'], {'interpolation': 'IMode.BICUBIC', 'antialias': '(True)'}), '(image_size // upscale_factor, interpolation=IMode.BICUBIC,\n antialias=True)\n', (2047, 2126), False, 'from torchvision import transforms\n'), ((2136, 2210), 'torchvision.transforms.Resize', 'transforms.Resize', (['image_size'], {'interpolation': 'IMode.BICUBIC', 'antialias': '(True)'}), '(image_size, interpolation=IMode.BICUBIC, antialias=True)\n', (2153, 2210), False, 'from torchvision import transforms\n'), ((2578, 2596), 'numpy.array', 'np.array', (['lr_image'], {}), '(lr_image)\n', (2586, 2596), True, 'import numpy as np\n'), ((2635, 2653), 'numpy.array', 'np.array', (['hr_image'], {}), '(hr_image)\n', (2643, 2653), True, 'import numpy as np\n'), ((4186, 4204), 'numpy.array', 'np.array', (['lr_image'], {}), '(lr_image)\n', (4194, 4204), True, 'import numpy as np\n'), ((4243, 4261), 'numpy.array', 'np.array', (['hr_image'], {}), '(hr_image)\n', (4251, 4261), True, 'import numpy as np\n'), ((5234, 5257), 'io.BytesIO', 'io.BytesIO', (['image_bytes'], {}), '(image_bytes)\n', (5244, 5257), False, 'import io\n'), ((5476, 5499), 'io.BytesIO', 'io.BytesIO', (['image_bytes'], {}), '(image_bytes)\n', (5486, 5499), False, 'import io\n')] |
# Imports
import numpy as np
# Utils
def first(a_list):
return a_list[0]
def last(a_list):
return a_list[-1]
def group_by(a_list, a_func=lambda x: x):
output_dict = {}
for a_elem in a_list:
key = a_func(a_elem)
if key in output_dict:
output_dict[key] = np.append(output_dict[key], a_elem[None, :], axis=0)
else:
output_dict[key] = np.array([a_elem])
return list(output_dict.values())
| [
"numpy.append",
"numpy.array"
] | [((306, 358), 'numpy.append', 'np.append', (['output_dict[key]', 'a_elem[None, :]'], {'axis': '(0)'}), '(output_dict[key], a_elem[None, :], axis=0)\n', (315, 358), True, 'import numpy as np\n'), ((404, 422), 'numpy.array', 'np.array', (['[a_elem]'], {}), '([a_elem])\n', (412, 422), True, 'import numpy as np\n')] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.